String lastIndexOf()
In JavaScript, String.lastIndexOf()
method is used to find the index of the last occurrence of the search string in the string.
Syntax
str.lastIndexOf(search, start)
str
is a string.search
is a string.start
is an integer, index position.
lastIndexOf()
method returns the index/position of the last occurrence of search
string in the string str
. Searching happens from the trail end of the string str
. If start
is provided, searching the string str
happens from that index at the end of the string str
.
Examples
1. Find index of last occurrence of 'banana'
search string, in string variable name
.
let name = 'apple banana cherry banana mango';
let index = name.lastIndexOf('banana');
console.log(index);
2. Find index of last occurrence of 'banana'
search string in string variable name
searching from from an index of 10
at the trailing end of the string.
let name = 'apple banana cherry banana mango';
let start = 10;
let index = name.lastIndexOf('banana', start);
console.log(index);
The last occurrence of the search string 'banana'
is ignored because the search happens from a position of 10 from the end.
3. Find index of last occurrence of 'banama'
search string in string variable name
.
let name = 'apple';
let index = name.lastIndexOf('banana');
console.log(index);
Since there is no occurrence of search string in the calling string, lastIndexOf()
returns -1
.