JavaScript String lastIndexOf()
Example
Search a string for the last occurrence of "planet":
let str = "Hello planet earth, you are a great planet.";
str.lastIndexOf("planet") // Returns 36
str.lastIndexOf("Planet") // Returns -1
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.
lastIndexOf() searches the string from the end to the beginning, but returns the index s
from the beginning, starting at position 0.
lastIndexOf() returns -1 if the value is not found.
lastindexOf() is case sensitive.
Tip: Also look at the indexOf() method.
Browser Support
lastIndexOf() is fully supported in all browsers:
| Chrome | IE | Edge | Firefox | Safari | Opera |
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
string.lastIndexOf(searchvalue, start)
Parameter Values
| Parameter | Description |
|---|---|
| searchvalue | Required. The string to search for |
| start | Optional. The position where to start the search (searching backwards). If omitted, the default value is the length of the string |
Technical Details
| Return Value: | A Number, representing the position where the specified searchvalue occurs for the last time, or -1 if it never occurs |
|---|---|
| JavaScript Version: | ECMAScript 1 |
More Examples
Example
Search a string for the last occurrence of "planet", starting the search at position 20:
let str = "Hello planet earth, you are a great planet.";
str.lastIndexOf("planet", 20) // Returns 6
Try it Yourself »

