Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

String.prototype.lastIndexOf

Finds the last occurrence of a text in a string.

Available since: ES1

Syntax

str.lastIndexOf(searchString, position)

Parameters

ParameterTypeDescription
searchStringstringThe text to find.
positionnumberOptional. 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:

11

The file extension is everything after the last dot:

const file = 'archive.tar.gz';
 
console.log(file.slice(file.lastIndexOf('.') + 1));

Output:

gz

Notes

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

Related recipes

In the tutorial

  • String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.

Thanks for reading!

Donate to the site — we work hard for you.