String

String.prototype.lastIndexOf

Returns the index of the last occurrence of a specified value, searching backwards from the specified position

Syntax

JavaScript
string.lastIndexOf(searchString, position?)

Parameters

ParameterTypeDescription
searchStringstringSubstring to search for
positionnumberPosition to start searching backwards from

Return Value

The index of the last occurrence, or -1

Examples

Basic Usage
const str = 'abcabc';
console.log(str.lastIndexOf('abc')); // 3
console.log(str.lastIndexOf('abc', 2)); // 0
Practical Example
const path = '/home/user/docs/file.txt';
const lastSlash = path.lastIndexOf('/');
console.log(path.slice(lastSlash + 1)); // 'file.txt'
Advanced Usage
const str = 'hello';
console.log(str.lastIndexOf('x')); // -1

Understanding 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

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.