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.
Syntax:
str.lastIndexOf(searchValue , index)
Parameters:
lastIndexOf() Method accepts 2 parameters which are discussed below:
- searchvalue: The searchvalue is the string that is to be searched in the base string.
- index: defines the starting index from where the searchvalue is to be searched in the base string backward
Return value:
This method returns the index of the string (0-based) where the searchvalue is found for the last time. If the searchvalue cannot be found in the string then the method returns -1
Example 1: Finding Last Occurrence of Substring in JavaScript
The function func()
initializes a string variable str
with the value 'GeeksforGeeks'. 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.
function func() {
let str = 'GeeksforGeeks';
let index = str.lastIndexOf('for');
console.log(index);
}
func();
Output
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 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();
Output
-1
We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.
Supported Browsers:
- Google Chrome 3
- Microsoft Edge 12
- Mozilla Firefox 3.0
- Safari 5
- Opera 10.5