JavaScript Glossary - Lesson #23

JavaScript String .lastIndexOf() Method

The 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.

js
""hello world scotch world"".lastIndexOf(""world"")
// 19
js
// 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 
js
const indexOfLastOccurence = string.lastIndexOf(searchParam, startIndex)

searchParam This is the string value to search for within the String object - required

startIndex 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 -1.

The method returns a number whch is the index of the last occurence of the search parameter.

This method is case sensitive

With the lastIndexOf() method, the index of the last occurrence of a particular string can be obtained.

js
// 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

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)