JavaScript Reference ยท String
String.prototype.lastIndexOf()
Reference for JavaScript String.prototype.lastIndexOf(): find the last index of a substring, understand the backward position argument and split paths and names.
The lastIndexOf() method searches a string from the end and returns the index where the last match begins, or -1 if the text does not occur.
It is the mirror image of indexOf(). It shines when the part you want is after the final separator: the file name after the last slash, or the extension after the last dot.
"canal".lastIndexOf("a"); // 3
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.lastIndexOf(searchString) string.lastIndexOf(searchString, position)
| Name | Description |
|---|---|
searchString |
The text to look for. It is converted to a string. |
position |
Optional. The largest index at which a match may begin. The search runs backwards from there. Defaults to the end of the string. Negative values and values below 0 count as 0; NaN counts as the end. |
Return value: the index of the last match that starts at or before position, or -1 if there is none.
Exceptions: none.
Usage notes
- The returned index is still the position of the match start, counted from the beginning of the string, not from the end.
positionlimits where a match may begin."canal".lastIndexOf("a", 2)returns1because theaat index3starts too late. Withposition0, only a match at index0can count.NaNis special. ApositionofNaN(orundefined) means "from the end", unlikeindexOf(), where it means "from the start".- Empty search text returns the string length (or
position, if that is smaller). - Always compare with
-1before slicing, as the extension example does. Otherwiseslice(lastIndexOf(".") + 1)would return the whole string for a name without a dot. - Case-sensitive, and it searches UTF-16 code units, like the other string search methods.
- Patterns: a regular expression is converted to a string, not used as a pattern. For the last match of a pattern, collect results with
matchAll()and take the last one. - Arrays have a method of the same name that compares whole elements; see
Array.prototype.lastIndexOf().
Browser support
lastIndexOf() works in every browser, old and new.