String.lastIndexOf() Find the last substring position
Last updated: 2026-10-13
String.lastIndexOf() Find the last substring position
lastIndexOf searches backwards and returns the start index of the last occurrence, or -1. It takes a string, not a regex.
| Category | Strings |
|---|---|
| ES version | ES1 (1997) |
📝 Syntax
string.lastIndexOf(searchString, position);
⚙️ Parameters
| searchString | Substring to find; case-sensitive. |
|---|---|
| position | Optional. Index to search backwards from; defaults to the end. |
Returns:The last occurrence index, or -1.
Mutates the original:No (returns a new value)
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
15
20
10
-1
💡 Tip Getting the file name: path.slice(path.lastIndexOf("/") + 1).
⚠️ Warning Use search for regex; loop with indexOf to find every position.
🌐 Browser support
| Browser | |||||
|---|---|---|---|---|---|
| String.lastIndexOf() | ✓ v1 | ✓ v12 | ✓ v1 | ✓ v1 | ✓ v3 |
| Supported by all modern browsers | |||||
🏷️ Related String Methods
💡 Related Cases
More case studies coming soon — check back later.
📚 Related Tutorials
❓ FAQ
QlastIndexOf vs indexOf?
AindexOf finds the first occurrence forward; lastIndexOf the last one backward.
QDoes it accept a regex?
ANo — a regex is coerced to its string form. Use search for regex.
QHow do I get a file extension?
Aconst dot = name.lastIndexOf("."); const ext = dot > -1 ? name.slice(dot + 1) : "";