JavaScript String lastIndexOf()
Examples
Search for the last occurrence of "planet":
let text = "Hello planet earth, you are a great planet.";
let result = text.lastIndexOf("planet");
Try it Yourself »
let text = "Hello planet earth, you are a great planet.";
let result = text.lastIndexOf("Planet");
Try it Yourself »
More examples below.
Description
The lastIndexOf()
method returns the index (position) of the last occurrence of a specified value in a string.
The lastIndexOf()
method searches the string from the end to the beginning.
The lastIndexOf()
method returns the index from the beginning (position 0).
The lastIndexOf()
method returns -1 if the value is not found.
The lastIndexOf()
method is case sensitive.
See Also:
Syntax
string.lastIndexOf(searchvalue, start)
Parameters
Parameter | Description |
searchvalue | Required. The string to search for. |
start | Optional. The position where to start. Default value is string length. |
Return Value
Type | Description |
A number | The position where the search-value occurs. -1 if it never occurs. |
More Examples
Search for the last occurrence of "planet", starting at position 20:
let text = "Hello planet earth, you are a great planet.";
let result = text.lastIndexOf("planet", 20);
Try it Yourself »
Browser Support
lastIndexOf()
is an ECMAScript1 (JavaScriopt 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |