JavaScript String lastIndexOf()

Summary: in this tutorial, you’ll learn how to use the JavaScript String lastIndexOf() method to locate the last occurrence of a substring in a string.

Introduction to the JavaScript String lastIndexOf() Method

The String.prototype.lastIndexOf() returns the last occurrence of a substring (substr) in a string (str).

str.lastIndexOf(substr, [, fromIndex]);Code language: JavaScript (javascript)

It returns -1 if the str does not contain the substr.

The lastIndexOf() method searches for the substring backward from the fromIndex. The fromIndex is optional and defaults to +Infinity. It means that if you omit the fromIndex, the search starts from the end of the string.

If the fromIndex is greater or equal to str.length, the lastIndexOf() will search for the substr in the whole string.

If the fromIndex is less than zero, the search behavior is the same as if the fromIndex were zero.

The lastIndexOf() always perform a case-sensitive search.

To find the index of the first occurrence of a substring within a string, you use the lastindexOf() method.

JavaScript String lastIndexOf() examples

Let’s take some examples of using the lastIndexOf() method.

1) Using lastIndexOf() method

This example uses the lastIndexOf() method to locate the last occurrence of the substring 'a' in the string 'JavaScript':

let str = 'JavaScript';
let index = str.lastIndexOf('a');

console.log(index);Code language: JavaScript (javascript)

Output:

3Code language: JavaScript (javascript)

If you pass the fromIndex argument to the string, the lastIndexOf() method will start searching backward from the fromIndex as shown in the following example:

let str = 'JavaScript';
let index = str.lastIndexOf('a',2);

console.log(index);Code language: JavaScript (javascript)

Output:

1Code language: JavaScript (javascript)

2) The lastIndexOf() and case-sensitivity

The lastIndexOf() is case-sensitive. The following example returns -1:

let str = 'Hello, World!';
let substr = 'L';

let index = str.lastIndexOf(substr);

console.log(index); // -1Code language: JavaScript (javascript)

To perform a case-insensitive search for the index of the last occurrence of a substring within a string, you can convert both substring and string to lowercase before applying the lastIndexOf() method as follows:

let str = 'Hello, World!';
let substr = 'L';

let index = str.toLocaleLowerCase().lastIndexOf(substr.toLocaleLowerCase());

console.log(index); // -1
Code language: JavaScript (javascript)

Summary

  • The lastIndexOf() returns the index of the last occurrence of a substring in a string, or -1 if the string does not contain the substring. It searches for the substring backward from the end of the string or from the fromIndex if this argument is available.
  • The lastIndexOf() carries a case-sensitive search.
Was this tutorial helpful ?