lastIndexOf method
The lastIndexOf method searches
for the last occurrence of a substring
in a string. In this case, it is
necessary to pay attention to the
character case specified in the first
parameter. The search is performed from
the end of the string. The method will
return the position of the first match
from the end, and if it is not found,
it will return -1. As the second
optional parameter, you can pass the
character number from where the
search should start.
Syntax
string.lastIndexOf(what to search, [where to start search]);
Example
Let's find the position of the last occurrence of a substring:
let str = 'ab cd cd cd ef';
let res = str.lastIndexOf('cd');
console.log(res);
The code execution result:
9
Example
Let's set the search start position:
let str = 'ab cd cd cd ef';
let res = str.lastIndexOf('cd', 8);
console.log(res);
The code execution result:
6
See also
-
the
startsWithmethod
that checks the start of a string -
the
endsWithmethod
that checks the end of a string -
the
indexOfmethod
that searches for the first occurrence of a substring -
the
includesmethod
that searches for a string -
the
atmethod
that searches for a string character