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
Fundamentals
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.
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:
Situation
Returns
Substring found
Last 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 position
str.length (e.g. "canal".lastIndexOf("") → 5)
Empty needle, position inside string
Same as position (e.g. "canal".lastIndexOf("", 2) → 2)
Case differs
-1 (e.g. "Whale".lastIndexOf("whale"))
Negative position
Only 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
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
Compare
📋 lastIndexOf() vs indexOf() vs includes()
lastIndexOf()
indexOf()
includes()
Result
Last index or -1
First index or -1
true / false
Best for
Rightmost match
Leftmost match
Simple contains checks
Case
Sensitive
Sensitive
Sensitive
Optional position
Match must start ≤ position
Search starts at/after position
Search starts at/after position
Hands-On
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'
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.
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.
Applications
🚀 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.
Important
📝 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.
Compatibility
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.
UniversalWidely available
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · 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.
Wrap Up
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.
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
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about String.lastIndexOf()
Last match index, or -1 when missing.
5
Core concepts
📝01
Returns
index / -1
API
🔙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.”