JavaScript - String lastIndexOf() method example

0 points
Created by:
// ONLINE-RUNNER:browser;

const text = 'ABC ABC';

console.log(text.lastIndexOf('A')); // 4
console.log(text.lastIndexOf('B')); // 5
console.log(text.lastIndexOf('C')); // 6

console.log(text.lastIndexOf('X')); // -1

console.log(text.lastIndexOf('ABC')); // 4
console.log(text.lastIndexOf('XYZ')); // -1

console.log(text.lastIndexOf('B', 2)); // 1
console.log(text.lastIndexOf('B', 6)); // 5

1. Documentation


String lastIndexOf(searchString)

String lastIndexOf(searchString, position)


searchString - a string to be searched for within the string,

position - the method looks for the specified substring to the position less than or equal to the position (+Infinity by default).

ResultThe method returns the index of the last occurrence of searchString or -1 if not found.

The lastIndexOf() method searches the entire calling string and returns the index of the last occurrence of the specified substring.

If the second argument is given (a number), the method returns the last occurrence of the specified substring at an index less than or equal to the specified number.


  1. String.prototype.lastIndexOf() - JavaScript | MDN

Alternative titles

  1. JavaScript - String.lastIndexOf() documentation with examples
  2. js - String lastIndexOf() method documentation with examples
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - String (documentation)

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂