Javascript String lastIndexOf() Function
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
The String lastIndexOf is a built-in JavaScript function that returns the index within the calling String object of the last occurrence of the specified value, searching backward from fromIndex. The lastIndexOf() method returns -1 if a value is not found. The syntax of lastIndexOf() function is following.
Syntax
string.lastIndexOf(searchvalue, start)
Arguments
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 the length of the string.
Example
See the following code example.
// app.js let str = 'Frozen II'; let index = str.lastIndexOf('en'); console.log(index);
See the following output.
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('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.
Case-sensitivity in Javascript String lastIndexOf
The lastIndexOf() method is case sensitive. So, it matches the exact case of the string. For example, the following expression returns -1.
// app.js console.log('AppDividend'.lastIndexOf('a'));
See the following output.
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.
That’s it for JavaScript lastIndexOf() function.