JavaScript lastIndexOf() method
The lastIndexOf()
method in JavaScript is used to determine the index of the last occurrence of a specified substring (search value) within a string. If the substring is not found, it returns -1
. This method is case-sensitive and can also accept an optional starting position from which to begin the search, searching backwards through the string.
Syntax:
searchValue
: The substring you want to search for within the string.fromIndex
(optional): An integer that specifies the index at which to start the search. The search will begin from this index and go backwards. If omitted, the search starts from the end of the string.
Return Value:
- It returns the zero-based index of the last occurrence of
searchValue
within the string. If the substring is not found, it returns-1
.
Example 1: Basic Usage
In this example, the substring "world"
is found at index 27
, which is the last occurrence in the string.
Example 2: Case Sensitivity
The lastIndexOf()
method is case-sensitive. This means that searching for "World"
will not match "world"
.
Example 3: Using fromIndex
You can specify a starting position for the search using the fromIndex
parameter. The search will begin at this index and go backwards through the string.
Example 4: Not Finding the Substring
If the specified substring is not found within the string, lastIndexOf()
will return -1
.
Example 5: Finding Empty Strings
When searching for an empty string (""
), lastIndexOf()
will return the index of the end of the string. This is because an empty string is considered to be at every index between characters, including the index after the last character.
Example 6: Finding the First Occurrence
If you want to find the first occurrence of a substring, you should use the indexOf()
method.
Summary:
- The
lastIndexOf()
method finds the index of the last occurrence of a specified substring within a string and returns-1
if not found. - It is case-sensitive and can take an optional
fromIndex
argument to specify where to start searching backwards. - Searching for an empty string returns the index equal to the length of the string since an empty substring is considered to be at every position.
- For finding the first occurrence of a substring, use the
indexOf()
method instead.