What is JavaScript String lastIndexOf() Function

The String lastIndexOf() is a built-in JavaScript function that returns a position of the last occurrence of a specified value in the string.

The String lastIndexOf() method accepts the value to search for, which is required, and an optional parameter, the starting index from where to search.

The lastIndexOf() function returns -1 if a value to search for never occurs.

The string is searched from the end to the beginning but returns an index starting at the beginning, at position 0. In other words, the search is done from right to left, starting at the end of the string.


string.lastIndexOf(searchvalue, start)


The searchValue parameter is required and is the string we are looking for.

The start parameter is optional and is where to start the search (searching backward). If omitted, the default value is the length of the string.


// app.js

let str = 'Frozen II';
let index = str.lastIndexOf('en');

See the following output.

Javascript String lastIndexOf Example

Characters in the string are indexed from left to right.

An index of the first character is 0, and the index of the last character is string.length – 1.

// app.js

console.log('AppDividend'.lastIndexOf('D', 2));
console.log('AppDividend'.lastIndexOf('App', 0));
console.log('AppDividend'.lastIndexOf('p', -5));
console.log('AppDividend'.lastIndexOf('D', 0));
console.log('AppDividend'.lastIndexOf('', 2));

See the output.

String.Prototype.lastIndexOf() Tutorial

Case-sensitivity in String lastIndexOf() function

The lastIndexOf() method is case-sensitive. So, it matches the exact cause of the string. For example, the following expression returns -1.

// app.js


See the following output.

Case-sensitivity in Javascript String lastIndexOf

The following code example uses indexOf and lastIndexOf to locate values.

// app.js

let data = 'FROZEN II Will Be A GOOD MOVIE';

console.log('The index of the first w from the beginning is ' + data.indexOf('F'));
console.log('The index of the first w from the end is ' + data.lastIndexOf('W')); 
console.log('The index of "new" from the beginning is ' + data.indexOf('GOOD'));
console.log('The index of "new" from the end is ' + data.lastIndexOf('GOOD'));

See the following output.

String lastIndexOf Example

That’s it for this function.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.