Javascript String lastIndexOf Example | String.Prototype.lastIndexOf() Tutorial

Javascript String lastIndexOf Example | String.Prototype.lastIndexOf() Tutorial

Javascript String lastIndexOf Example | String.Prototype.lastIndexOf() Tutorial is today’s topic. The lastIndexOf() method 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. Returns -1 if a value is not found. The syntax of lastIndexOf() function is following.

Syntax

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');
console.log(index);

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('A'));
console.log('AppDividend'.lastIndexOf('D', 2));
console.log('AppDividend'.lastIndexOf('App', 0));
console.log('AppDividend'.lastIndexOf('A'));
console.log('AppDividend'.lastIndexOf('p', -5));
console.log('AppDividend'.lastIndexOf('D', 0));
console.log('AppDividend'.lastIndexOf(''));
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

console.log('AppDividend'.lastIndexOf('a'));

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 | String.Prototype.lastIndexOf() Tutorial is over.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *