Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
"canal".lastIndexOf("a"); // 3

Try it

JS Searching backwards

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS File name and extension

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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.
  • position limits where a match may begin. "canal".lastIndexOf("a", 2) returns 1 because the a at index 3 starts too late. With position 0, only a match at index 0 can count.
  • NaN is special. A position of NaN (or undefined) means "from the end", unlike indexOf(), where it means "from the start".
  • Empty search text returns the string length (or position, if that is smaller).
  • Always compare with -1 before slicing, as the extension example does. Otherwise slice(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.