lastIndexOf() method returns the last position within a String object which an element can be found. The search starts from the last position of the String object. The method will return
-1 if the specified parameter cannot be found.
""hello world scotch world"".lastIndexOf(""world"") // 19
// List of names const names = "sean, becky, liz, wale, blue, becky, john" const searchItem = "becky" // Find last occurrence of "becky" const lastSimilarName = names.lastIndexOf(searchItem) // Display result console.log(lastSimilarName) // 30
const indexOfLastOccurence = string.lastIndexOf(searchParam, startIndex)
This is the string value to search for within the String object -
This is the index at which the search will begin. Search typically begins from the string
.length - 1 index, which is the last position of the object. If the length of the provided string is
0, or if no item was found, it returns
The method returns a number whch is the index of the last occurence of the search parameter.
This method is case sensitive
lastIndexOf() method, the index of the last occurrence of a particular string can be obtained.
// New string const words = "the house, the car, the book, the mac and the cheese" // Specify search item const searchTerm = "the" // Search the string let lastIndexOfWord = words.lastIndexOf(searchTerm) // Display last index console.log(lastIndexOfWord) // 42
Want to improve your coding and design skills?
I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.
We value your privacy. 1-click unsubscribe.
Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.
What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)