JavaScript String lastIndexOf() Method Examples
Example 1: Finding Last Occurrence of Substring in JavaScript
The function func()
initializes a string variable str
with the value ‘w3wiki’. It then uses the lastIndexOf()
method to find the index of the last occurrence of the substring ‘for’ within the string str
. The index, which is 5
, is then printed to the console.
JavaScript
function func() { let str = 'w3wiki' ; let index = str.lastIndexOf( 'for' ); console.log(index); } func(); |
5
Example 2: Case-sensitive Search with JavaScript’s lastIndexOf()
The func()
function initializes a string variable str
with the value ‘Departed Train’. It then uses the lastIndexOf()
method to find the index of the last occurrence of the substring ‘train’ (case-sensitive) within the string str
. Since ‘train’ is not found in ‘Departed Train’, -1
is printed to the console.
JavaScript
// JavaScript to illustrate lastIndexOf() method function func() { // Original string let str = 'Departed Train' ; // Finding index of occurrence of 'train' let index = str.lastIndexOf( 'train' ); console.log(index); } func(); |
-1
We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.
Supported Browsers:
- Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Internet Explorer 6 and above
- Opera 3 and above
- Safari 1 and above
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
JavaScript String lastIndexOf() Method
The lastIndexOf()
method in JavaScript is used to search for the last occurrence of a specified substring within a string.
It returns the index of the last occurrence of the specified substring, or -1 if the substring is not found.