We can use the String.LastIndexOf()
method to get the index position of the last time a particular string value appears in the given string. This method searches a string from end to beginning.
string.lastIndexOf(substring)
substring
: This is the value, string value, or substring for which we want to get the index position of its last occurrence in a string.
The value returned is an integer that represents the index position of the last occurrence of a specified substring in a string. If the value is not found, then a -1
is returned. It is case-sensitive.
Let's look at the code below:
export {}// create some stringslet greeting:string = "Welcome to Edpresso"let proverb:string = "If a child washed his hands, he could eat with kings"let author:string = "Chinua Achebe"let book:string = "Things fall apart"// get index position of last occurence of some string valuesconsole.log(greeting.lastIndexOf("to"))console.log(proverb.lastIndexOf("M"))console.log(author.lastIndexOf("e"))console.log(book.lastIndexOf("fall"))
In the code above:
lastIndexOf()
method to get the last occurrence of a string value in a string and log it to the console.