The syntax of the lastIndexOf()
method is:
str.lastIndexOf(searchValue, fromIndex)
Here, str is a string.
lastIndexOf() Parameters
The lastIndexOf()
method takes in:
- searchValue - The value to search for in the string. If no string is provided explicitly, fromIndex is returned.
- fromIndex (optional) - The index to start searching the string backwards. By default it is +Infinity.
Notes:
- If fromIndex >= string.length, the whole string is searched.
- If fromIndex < 0, it is considered to be the same as 0.
Return value from lastIndexOf()
- Returns the last index of the value in the string if it is present at least once.
- Returns -1 if the value is not found in the string.
Note: The lastIndexOf()
method is case sensitive.
Example: Using lastIndexOf() method
var str = "JavaScript is the world's most misunderstood programming language.";
// lastIndexOf() returns the last occurance
var index1 = str.lastIndexOf("language");
console.log(index1); // 57
var index2 = str.lastIndexOf("p");
console.log(index2); // 45
// second argument specifies the search's start index
var index3 = str.lastIndexOf("p", 44);
console.log(index3); // 8
// lastIndexOf returns -1 if not found
var index4 = str.lastIndexOf("Python");
console.log(index4); // -1
Output
57 45 8 -1
Recommended Readings: