Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

String.prototype.lastIndexOf — last substring occurrence

lastIndexOf() returns the index of the last substring occurrence or -1. The optional position limits where a match starts, not where it ends.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

str.lastIndexOf(searchString[, position])

String.prototype.lastIndexOf performs a case-sensitive substring search and returns the greatest matching zero-based index, or -1. It does not modify the string. Indices count UTF-16 code units, not necessarily complete user-perceived characters.

The optional position sets the greatest allowed starting index of a match; the match may end beyond it. Omitting the argument, passing undefined, or passing NaN allows searching the whole string. Fractional values are truncated toward zero, negative values are clamped to 0, and oversized values do not extend the search beyond the string. Thus, a negative position can still find a match starting at 0.

An empty searchString matches at every code-unit boundary; without position, the result is the string length. searchString is converted to a string: omitting it searches for "undefined". The method does not interpret regular expressions.

In the example, "ana" starts at indices 1 and 3. Use !== -1 to test presence: index 0 is a valid result even though it is falsy in a condition.

Examples

const text = "banana";
console.log(text.lastIndexOf("ana"));
console.log(text.lastIndexOf("ana", 2));
console.log(text.lastIndexOf("x"));
console.log(text.lastIndexOf(""));
console.log(text.lastIndexOf("b", -1));

Result

3
1
-1
6
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources