UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ String/ String.prototype.lastIndexOf()

The lastIndexOf() method of String values searches this string and returns the index of the last occurrence of the specified substring. It takes an optional starting position and returns the last occurrence of the specified substring at an index less than or equal to the specified number.

Syntax

lastIndexOf(searchString)
lastIndexOf(searchString, position)

Parameters

Return value

The index of the last occurrence of searchString found, or -1 if not found.

Description

Strings are zero-indexed: The index of a string's first character is 0, and the index of a string's last character is the length of the string minus 1.

"canal".lastIndexOf("a"); // returns 3
"canal".lastIndexOf("a", 2); // returns 1
"canal".lastIndexOf("a", 0); // returns -1
"canal".lastIndexOf("x"); // returns -1
"canal".lastIndexOf("c", -5); // returns 0
"canal".lastIndexOf("c", 0); // returns 0
"canal".lastIndexOf(""); // returns 5
"canal".lastIndexOf("", 2); // returns 2

Case-sensitivity

The lastIndexOf() method is case sensitive. For example, the following expression returns -1:

"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1

Examples

Using indexOf() and lastIndexOf()

The following example uses indexOf() and lastIndexOf() to locate values in the string "Brave, Brave New World".

const anyString = "Brave, Brave New World";

console.log(anyString.indexOf("Brave")); // 0
console.log(anyString.lastIndexOf("Brave")); // 7

Specifications

Browser compatibility

See also