String.lastIndexOf() , which is used to find the last occurrence of a character or substring in a string.
Note that:- If the
substring or occurrence character does not found in
string, It returns -1.
The following syntax demonstrates the
String.lastIndexOf() method; as shown below:
string.lastIndexOf(substring, [, startIndex]);
Remember that, this js
lastIndexOf() method searches for the substring backward from the
startIndex. and this
startIndex is an optional parameter.
Note that, if you ignore the
startIndex, the search starts from the end of the given string.
This is a very important for note that, The
lastIndexOf() always perform a case-sensitive search.
Now i will take first example using
lastIndexOf() method to find the last occurrence of a character or substring
'r' in the string
'programming'; as shown below:
let str = 'programming'; let index = str.lastIndexOf('r'); console.log(index);
I will take second example with case sensitive string; as shown below:
In this tutorial, you have learned everything about the
lastIndexOf() string method in js with various examples.