Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript String lastIndexOf()

The lastIndexOf() method retrieves the index of the final occurrence of a specified text within a string.

Example

let text = “Please locate where ‘locate’ occurs!”;
let index = text.lastIndexOf(“locate”);

Both indexOf() and lastIndexOf() return -1 when the specified text is not found within the string.

Example

let text = “Please locate where ‘locate’ occurs!”;
let index = text.lastIndexOf(“John”);

Both methods allow for specifying a second parameter, which serves as the starting position for the search.

Example

let text = “Please locate where ‘locate’ occurs!”;
let index = text.indexOf(“locate”15);

The lastIndexOf() method conducts a backward search (from the end to the beginning). In other words, if the second parameter is set to 15, the search initiates at position 15 and proceeds towards the start of the string.

Example

let text = “Please locate where ‘locate’ occurs!”;
text.lastIndexOf(“locate”15);