String.prototype.lastIndexOf
Returns the index of the last occurrence of a specified value, searching backwards from the specified position
Syntax
string.lastIndexOf(searchString, position?)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchString | string | Substring to search for |
| position | number | Position to start searching backwards from |
Return Value
The index of the last occurrence, or -1
Examples
const str = 'abcabc';
console.log(str.lastIndexOf('abc')); // 3
console.log(str.lastIndexOf('abc', 2)); // 0const path = '/home/user/docs/file.txt';
const lastSlash = path.lastIndexOf('/');
console.log(path.slice(lastSlash + 1)); // 'file.txt'const str = 'hello';
console.log(str.lastIndexOf('x')); // -1Understanding String.prototype.lastIndexOf
The String.prototype.lastIndexOf method in JavaScript returns the index of the last occurrence of a specified value, searching backwards from the specified position. It belongs to the String object and is one of the most widely used methods for working with string values in modern JavaScript and TypeScript applications.
The method signature is string.lastIndexOf(searchString, position?). It accepts 2 parameters: searchString, position. When called, it returns the index of the last occurrence, or -1. Understanding when and how to use lastIndexOf() helps you write more expressive, readable code.
Common use cases for String.prototype.lastIndexOf include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like string-indexof, string-includes, string-search, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for String.prototype.lastIndexOf is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
String.prototype.indexOfReturns the index of the first occurrence of a specified value in a string, or -1 if not found
String.prototype.includesDetermines whether one string may be found within another string, returning true or false
String.prototype.searchExecutes a search for a match between a regular expression and this string, returning the index of the first match
More String Methods
Other methods in the String object
Related Tools
More String Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.