Latest Code Tutorials

Javascript String lastIndexOf: How to Use lastIndexOf()


Javascript String lastIndexOf() is an inbuilt function that returns a position of the last occurrence of a specified value in the string. The string is searched from an end to the beginning, but returns an index starting at the beginning, at position 0. This method returns -1 if a value to search for never occurs. The lastIndexOf() method is case sensitive!

Javascript String lastIndexOf Example

Javascript String lastIndexOf method returns the index within the calling String object of the last occurrence of the specified value, searching backward from fromIndex. It returns -1 if a value is not found.

The syntax of lastIndexOf() function is following.


string.lastIndexOf(searchvalue, start)

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

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

See the following code example.

// 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 the 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 Javascript String lastIndexOf

The lastIndexOf() method is case sensitive. 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

Finally, Javascript String lastIndexOf() example is over.

Leave A Reply

Your email address will not be published.

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