JavaScript(JS) string method - lastindexof

The lastIndexOf() method is a string method in JavaScript that is used to find the last occurrence of a specified substring in a given string. It returns the index of the last occurrence of the specified substring, or -1 if the substring is not found.

Here is the syntax for the lastIndexOf() method:

str.lastIndexOf(searchValue[, fromIndex])
‮S‬ource:www.theitroad.com

Here, str is the original string you want to search in, and searchValue is the substring you want to search for. The optional fromIndex parameter specifies the position within the str to start the search from in reverse order, and if not specified, it starts from the end of the string.

The lastIndexOf() method returns the index of the last occurrence of the specified substring within the string. If the substring is not found, it returns -1.

Here is an example of using the lastIndexOf() method:

let str = "Hello World";
console.log(str.lastIndexOf("o")); // 7
console.log(str.lastIndexOf("x")); // -1
console.log(str.lastIndexOf("o", 5)); // 4

In the first console.log(), the lastIndexOf() method returns 7 because the last occurrence of the substring "o" in the str is at the 7th index. In the second console.log(), it returns -1 because the substring "x" is not found in the str. In the third console.log(), it returns 4 because the last occurrence of the substring "o" in the str before the 5th index in reverse order is at the 4th index.