Description
The JavaScript method lastIndexOf()
returns the index of the last occurrence of a specific substring in a string.
Syntax
The method lastIndexOf()
has the below syntax
It checks for the substring searchString
in the string str
from index fromIndex
to end of the string str
.
str.lastIndexOf(searchString, fromIndex)
Parameters
The method lastIndexOf()
accepts the below parameters.
searchString
- It is the string to be searched for within the string
str
.
fromIndex
(optional)
- It is the index within
str
to begin searching forsearchString
in backward. - The default value is Infinity.
Result
The method lastIndexOf()
returns the below values.
- Returns the index of the last occurrence of
searchString
if found instr
, otherwise returns-1
.
Example 1: Using the Method
The method returns the index of the last occurrence of a substring in a string.
var str = "Hello World!";
// Finding the index of the last occurrence of "o"
document.write(str.lastIndexOf("o")); // Prints: 7
// Finding the index of the last occurrence of empty string
document.write(str.lastIndexOf("")); // Prints: 12
// Finding the index of the last occurrence of "abc"
document.write(str.lastIndexOf("abc")); // Prints: -1
Output:
7
13
-1
Example 2: Using the Method with From Index
The fromIndex
is used to find the position from where the backward search must perform within the string.
var str = "Hello World!";
// Searches for "o" from index 2
document.write(str.lastIndexOf("o", 10)); // Prints: 7
// Searches for "o" from index 5
document.write(str.lastIndexOf("o", 5)); // Prints: 4
// Searches for "o" from index 10
document.write(str.lastIndexOf("o", 2)); // Prints: -1
Output:
7
4
-1
Overall
The JavaScript method lastIndexOf()
returns the index of the last occurrence of a specific substring in a string.