Find the Index of the Last Occurrence in a String in JS

avatar

Borislav Hadzhiev

Wed Oct 27 20211 min read

banner

Photo by freestocks

Find the Index of the Last Occurrence in a String #

Use the lastIndexOf() method to find the index of the last occurrence in a string. The method returns the index of the last occurrence of the provided value in the string. If the value is not found in the string, -1 is returned.

index.js
const str = 'hello world'; console.log(str.lastIndexOf('l')); // ๐Ÿ‘‰๏ธ 9

We used the String.lastIndexOf method to find the last index of the character l in the string hello world.

The only parameter we passed to the method is the substring we want to search for.

Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0, and the index of the last - string.length - 1.

If the substring is not found in the string, the lastIndexOf method returns -1.

index.js
const str = 'hello world'; console.log(str.lastIndexOf('bye')); // ๐Ÿ‘‰๏ธ -1

Note that the lastIndexOf method is case sensitive.

index.js
const str = 'hello world'; console.log(str.lastIndexOf('L')); // ๐Ÿ‘‰๏ธ -1

To use the method in a case-insensitive manner, call the toLowerCase() method on both - the string and the substring.

index.js
const str = 'hello world'; const substring = 'L'; // ๐Ÿ‘‡๏ธ 9 console.log( str.toLowerCase().lastIndexOf(substring.toLowerCase()) );

By converting both strings to lowercase before calling the lastIndexOf method, we are able to use the method in a case-insensitive manner.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee