JavaScript String lastIndexOf() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.lastIndexOf() returns the last index of a substring, or -1 if it is missing (same API as MDN String.prototype.lastIndexOf()). Learn the optional from-position, case sensitivity, empty-string quirks, how it differs from indexOf(), five examples, and try-it labs.

01

Kind

Instance method

02

Returns

index or -1

03

Case

Sensitive

04

vs indexOf

Last vs first

05

Mutates?

No

06

Baseline

Widely available

Introduction

When a substring appears more than once and you care about the rightmost match — file extensions, the last slash in a path, the final keyword — use lastIndexOf(). It returns a zero-based index, or -1 when nothing matches.

The search is case-sensitive. An optional second argument limits the search to matches that start at or before that index. For the first match from the left, use indexOf().

💡
Beginner tip

Test for a miss with === -1. Index 0 is still a valid match — for example when the only occurrence is at the start.

This page is part of JavaScript String Methods. Related topics include indexOf() and includes().

Understanding the lastIndexOf() Method

lastIndexOf(searchString, position) looks for the last place the substring begins at an index ≤ position (default: end of the string).

  • Indexes are zero-based — the first character is at 0.
  • Missing substring — returns -1.
  • Matching is case-sensitive and exact.
  • position < 0 behaves like searching only at index 0.

📝 Syntax

General forms of String.prototype.lastIndexOf:

JavaScript
str.lastIndexOf(searchString)
str.lastIndexOf(searchString, position)

Parameters

  • searchString — the substring to look for. Coerced to a string (undefined becomes "undefined").
  • position (optional) — only consider matches that start at an index ≤ this value. Defaults to searching the whole string. If greater than str.length, the entire string is searched. If less than 0, only index 0 is considered.

Return value

A number — the last matching index, or -1. Special cases:

SituationReturns
Substring foundLast index ≤ position (e.g. "canal".lastIndexOf("a")3)
Substring missing-1
Match exists but starts after position-1 (e.g. "hello world".lastIndexOf("world", 4))
Empty needle, no / high positionstr.length (e.g. "canal".lastIndexOf("")5)
Empty needle, position inside stringSame as position (e.g. "canal".lastIndexOf("", 2)2)
Case differs-1 (e.g. "Whale".lastIndexOf("whale"))
Negative positionOnly index 0 is considered

Common patterns

JavaScript
"canal".lastIndexOf("a");     // 3
"canal".lastIndexOf("a", 2);  // 1
"canal".lastIndexOf("x");     // -1

const path = "docs/guides/intro.md";
path.lastIndexOf(".");        // 16 — start of extension
path.slice(path.lastIndexOf(".") + 1);  // "md"

// First vs last:
"Brave, Brave New World".indexOf("Brave");      // 0
"Brave, Brave New World".lastIndexOf("Brave");  // 7

⚡ Quick Reference

GoalCode
Last indexstr.lastIndexOf(needle)
Search at/before an indexstr.lastIndexOf(needle, pos)
Not found?=== -1
First index insteadstr.indexOf(needle)
Case-insensitivestr.toLowerCase().lastIndexOf(needle.toLowerCase())
File extensionname.slice(name.lastIndexOf(".") + 1)

🔍 At a Glance

Four facts to remember about String.lastIndexOf().

Returns
number

Last index or -1

Case
sensitive

Normalize if needed

Miss
-1

Not 0, not false

Mutates
no

Strings stay immutable

📋 lastIndexOf() vs indexOf() vs includes()

lastIndexOf()indexOf()includes()
ResultLast index or -1First index or -1true / false
Best forRightmost matchLeftmost matchSimple contains checks
CaseSensitiveSensitiveSensitive
Optional positionMatch must start ≤ positionSearch starts at/after positionSearch starts at/after position

Examples Gallery

Examples follow MDN String.lastIndexOf() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Find the last index of a substring.

Example 1 — Basic lastIndexOf()

MDN-style lookup: last "dog" in a sentence.

JavaScript
const paragraph = "I think Ruth's dog is cuter than your dog!";
const searchTerm = "dog";

`Index of the last "${searchTerm}" is ${paragraph.lastIndexOf(searchTerm)}`;
// 'Index of the last "dog" is 38'
Try It Yourself

How It Works

There are two "dog" tokens. lastIndexOf returns the start of the second one (38). indexOf would return the first (15).

Example 2 — indexOf() vs lastIndexOf()

MDN demo: same needle, first vs last occurrence.

JavaScript
const anyString = "Brave, Brave New World";

anyString.indexOf("Brave");      // 0
anyString.lastIndexOf("Brave");  // 7

"canal".lastIndexOf("a");     // 3
"canal".lastIndexOf("a", 2);  // 1
"canal".lastIndexOf("a", 0);  // -1
"canal".lastIndexOf("x");     // -1
Try It Yourself

How It Works

With position 2, only the "a" at index 1 is allowed (the one at 3 starts after 2). With position 0, no "a" starts at or before 0, so you get -1.

📈 Practical Patterns

From-position limits, case folding, and empty needles.

Example 3 — Optional position Limits

MDN rules: match start must be ≤ position.

JavaScript
const s = "hello world hello";

s.lastIndexOf("world", 4);   // -1  (match at 6 is not ≤ 4)
s.lastIndexOf("hello", 99);  // 12  (last hello still ≤ 99)
s.lastIndexOf("hello", 0);   // 0   (only look at index 0)
s.lastIndexOf("hello", -5);  // 0   (negative → same as 0)

"canal".lastIndexOf("c", -5); // 0
"canal".lastIndexOf("c", 0);  // 0
Try It Yourself

How It Works

Think of position as a right-hand fence: the match’s start index must sit on or left of that fence. High values search everything; negatives only allow index 0.

Example 4 — Case Sensitivity

MDN note: capitalization must match exactly.

JavaScript
"Blue Whale, Killer Whale".lastIndexOf("Whale");  // 19
"Blue Whale, Killer Whale".lastIndexOf("blue");   // -1

"Blue Whale, Killer Whale"
  .toLowerCase()
  .lastIndexOf("blue");  // 0
Try It Yourself

How It Works

Lower-casing the haystack (and needle when needed) makes the search ignore capital letters — same idea as with indexOf.

Example 5 — Empty String and File Extension

Empty-needle quirks plus a practical rightmost-dot pattern.

JavaScript
"canal".lastIndexOf("");     // 5  (length)
"canal".lastIndexOf("", 2);  // 2

const file = "archive.tar.gz";
const dot = file.lastIndexOf(".");
file.slice(dot + 1);         // "gz"
file.slice(0, dot);          // "archive.tar"

file.lastIndexOf("zip") !== -1;  // false
file.includes("tar");            // true (clearer boolean)
Try It Yourself

How It Works

An empty needle “matches” at the from-position (or at the end). For real text, lastIndexOf(".") is a classic way to find the last extension separator in a filename.

🚀 Common Use Cases

  • File extensions — last "." before slicing the suffix.
  • Path segments — last "/" or "\\" to get the basename.
  • Rightmost keyword — find the final occurrence of a token.
  • Pair with indexOf — compare first vs last positions.
  • Bounded search — pass position to ignore matches past a fence.
  • Prefer includes for booleans — clearer intent for yes/no checks.

🧠 How lastIndexOf() Finds an Index

1

Receive needle + from-position

Coerce searchString; treat missing position as “search everything”.

Input
2

Scan for the rightmost match

Only consider exact matches that start at an index ≤ position.

Search
3

Handle empty needle

Empty string matches at position (or at length when searching the whole string).

Special
4

Return index or -1

Use the number for slicing, comparing first/last, or an existence check.

📝 Notes

  • lastIndexOf() is case-sensitive.
  • A miss returns -1 — never confuse that with index 0.
  • The optional position is a right fence: match start must be ≤ that index.
  • Negative position only considers index 0.
  • Empty searchString has special return rules (see the table above).
  • Omitting the needle (or passing undefined) searches for "undefined".
  • Prefer includes() when you only need a boolean.

Browser & Runtime Support

String.prototype.lastIndexOf() is Baseline Widely available — supported across browsers for many years.

Baseline · Widely available

String.lastIndexOf()

Safe for production. Use lastIndexOf() when you need the rightmost match index; prefer includes() for simple true/false checks.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
lastIndexOf() Excellent

Bottom line: Use String.lastIndexOf() to locate the last substring index. Remember -1 means missing, searches are case-sensitive, and position limits which matches count.

Conclusion

String.prototype.lastIndexOf() finds the last index of a substring (or -1 if missing), with an optional from-position that fences matches from the right. Pair it with indexOf() when you need both ends, and keep case rules and empty-needle quirks in mind.

Continue with startsWith(), includes(), or the String methods hub.

💡 Best Practices

✅ Do

  • Use lastIndexOf when you need the rightmost match
  • Check misses with === -1
  • Use position to ignore matches past a fence
  • Prefer includes() for simple contains checks
  • Normalize case when matches should ignore capitalization

❌ Don’t

  • Treat index 0 as “not found”
  • Confuse position with indexOf’s start-from rule
  • Forget that searches are case-sensitive
  • Ignore empty-needle special cases
  • Use lastIndexOf when a boolean is all you need

Key Takeaways

Knowledge Unlocked

Five things to remember about String.lastIndexOf()

Last match index, or -1 when missing.

5
Core concepts
🔙 02

Direction

rightmost

Search
03

Miss

-1

Bounds
04

vs indexOf

last vs first

Compare
📄 05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.lastIndexOf(searchString, position?) returns the zero-based index of the last occurrence of searchString at or before position. If nothing is found, it returns -1.
Yes. "Blue Whale, Killer Whale".lastIndexOf("blue") returns -1. Normalize with toLowerCase() when you need a case-insensitive search.
indexOf() finds the first match from the start (or from a start position forward). lastIndexOf() finds the last match at or before a from-position (default: end of the string).
Only matches whose start index is less than or equal to position are considered. If position is past the end, the whole string is searched. If position is less than 0, only index 0 is considered.
With no position it returns str.length. With a position inside the string it returns that position (clamped). Empty needles always “match” at a boundary.
No. Strings are immutable. lastIndexOf() only reads and returns a number.
Did you know?

The position argument for lastIndexOf is easy to mix up with indexOf. For indexOf, it means “start looking here and go right.” For lastIndexOf, it means “only accept matches that start at or left of here.”

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful