JavaScript String lastIndexOf | Search Last Substring In String

JavaScript String lastIndexOf | Search Last Substring In String

In this tutorial, you will learn about JavaScript String lastIndexOf() and how to use it.

JavaScript String lastIndexOf()

In JavaScript, String.lastIndexOf() is a string method that is used to find the last occurrence of a substring in a string.

The following syntax demonstrates the String.lastIndexOf()  method:

string.lastIndexOf(substring, [, startIndex]);

If the substring does not found instring, It returns -1.

Remember that, this js lastIndexOf() method searches for the substring backward from the startIndex. and this startIndex is an optional parameter.

Note that, if you ignore the startIndex, the search starts from the end of the given string.

This is a very important for note that, The lastIndexOf() always perform a case-sensitive search.

If you find the index of the first occurrence of a substring within a string, you useindexOf() method.

Examples: JavaScript String lastIndexOf()

Let’s take look at some examples of using the lastIndexOf() method:

1) Occurrence is Found using lastIndexOf() method

This is the first example of lastIndexOf() method and find the last occurrence of the substring 'r' in the string 'programming':

let str = 'programming';
let index = str.lastIndexOf('r');

console.log(index);

Output:

4

If you pass the startIndex parameter to the string, the lastIndexOf() method will start searching backward from the startIndex, you can see the following example:

let str = 'programming';
let index = str.lastIndexOf('r', 2);

console.log(index);

Output:

1

2) The lastIndexOf() and case-sensitivity

The lastIndexOf() is case-sensitive. See the following example:

let str = 'JavaScript Programming language';
let substr = 's';

let index = str.lastIndexOf(substr);

console.log(index); // -1

So first of all, convert given string and substring into lowercase string and then perform a case-insensitive search the last substring in the javascript string using lastIndexOf() the method.

See the following example:

let str = 'JavaScript Programming language';

let substr = 'S';

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

console.log(index); // 4

Conclusion

In this tutorial, you have learned everything about the lastIndexOf() string method in js with various examples.

Leave a Reply

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