String.prototype.lastIndexOf
Finds the last occurrence of a text in a string.
Available since: ES1
Syntax
str.lastIndexOf(searchString, position)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchString | string | The text to find. |
| position | number | Optional. Do not search past this position. From the end of the string by default. |
Return value
numberThe position of the last occurrence, or -1 if the text is not found.
Examples
The last dot in a file name:
console.log('archive.tar.gz'.lastIndexOf('.'));Output:
11The file extension is everything after the last dot:
const file = 'archive.tar.gz';
console.log(file.slice(file.lastIndexOf('.') + 1));Output:
gzNotes
If the text is not found the method returns -1, and slice(-1 + 1) returns the whole string — check the result before using it.
See also
- String.prototype.indexOf — Finds the position of the first occurrence of a substring.
- String.prototype.slice — Returns part of a string.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.