Course contentsShow
← JavaScript
Lesson 159 of 2,7235. StringsFree lesson

lastIndexOf(): Finding from the End

Search for a substring starting from the end of the string and return its last position.

lastIndexOf(): Finding from the End

You'll learn how to search for a substring starting from the end of a string and find its last occurrence.


The Core Idea

While indexOf() searches from the beginning of a string and returns the first match, lastIndexOf() works in reverse—it searches from the end and returns the position of the last occurrence of your substring.

Think of it like reading a book: indexOf() is scanning forward from page 1, while lastIndexOf() starts at the back cover and works backward, stopping at the last place your word appears.

How It Works

const phrase = "To be or not to be";

const firstBe = phrase.indexOf("be");      // 3 (first "be")
const lastBe = phrase.lastIndexOf("be");   // 16 (last "be")

Just like indexOf(), lastIndexOf() returns -1 if the substring isn't found:

const text = "JavaScript is fun";
console.log(text.lastIndexOf("Python"));  // -1

Searching from a Specific Position

You can also provide a second parameter to limit where the search starts (from the end):

const message = "hello hello hello";
console.log(message.lastIndexOf("hello", 10));  // 6 (searches backward from index 10)

When to Use It

Use lastIndexOf() when you need to find the last occurrence of something, like finding the file extension separator in a filename:

const filename = "document.backup.txt";
const lastDot = filename.lastIndexOf(".");  // 15 (the final dot)

Key Takeaway: lastIndexOf() searches backward through a string and returns the position of the last occurrence of a substring, or -1 if not found—perfect for when you need the final match instead of the first.