JavaScript String Search Indexof and Lastindexof Guide

Learn JavaScript indexOf, lastIndexOf, and search for finding substring positions. Clear examples showing how to locate text and handle no-match results.

4 min read

JavaScript provides three methods for finding where a substring appears within a string: indexOf, lastIndexOf, and search. They return the character position of a match, or -1 when nothing is found.

javascriptjavascript
const text = "JavaScript is fun. JavaScript is powerful.";
 
console.log(text.indexOf("JavaScript"));
console.log(text.lastIndexOf("JavaScript"));
console.log(text.search(/power/));

The first prints 0 because "JavaScript" starts at position zero. The second prints 20, the position of the last occurrence. The third prints 28 because the regex /power/ matches "power" starting at position 28.

These methods complement the boolean-checking methods includes, startsWith, and endsWith. See the guide to includes, startsWith, and endsWith for when you only need a yes or no answer.

indexOf() -- find the first match

The indexOf method scans a string from left to right and returns the position of the first match. It accepts an optional second argument: the position to start searching from.

javascriptjavascript
const sentence = "The quick brown fox jumps over the lazy dog";
 
console.log(sentence.indexOf("the"));
console.log(sentence.indexOf("the", 10));

The first prints 31 because the lowercase "the" first appears before "lazy". The uppercase "The" at position 0 does not match because indexOf is case-sensitive.

The second call starts searching from position 10, skipping past "quick brown fox jumps over". It still finds "the" at position 31.

The most common beginner mistake is treating the return value as a boolean:

javascriptjavascript
const text = "Hello";
 
if (text.indexOf("H")) {
  console.log("Found");   // Does NOT print!
}

This does not print anything because indexOf returns 0 for "H" at the first position, and 0 is falsy in JavaScript. Always compare explicitly:

javascriptjavascript
if (text.indexOf("H") !== -1) {
  console.log("Found");   // Prints correctly
}

lastIndexOf() -- find the last match

The lastIndexOf method works the same way as indexOf but scans from right to left, returning the position of the last match.

javascriptjavascript
const path = "/users/profile/settings/profile";
 
console.log(path.lastIndexOf("profile"));
console.log(path.indexOf("profile"));

The first prints 26 because "profile" appears last at position 26. The second prints 7 because the first "profile" starts at position 7.

lastIndexOf also accepts a starting position, but it searches backward from that position:

javascriptjavascript
const word = "banana";
 
console.log(word.lastIndexOf("a"));
console.log(word.lastIndexOf("a", 2));

The first prints 5, the position of the last "a". The second prints 1 because it only considers characters up to position 2, and within "ban", the last "a" is at position 1.

The search method behaves like indexOf but accepts a regular expression instead of a plain string. It returns the position of the first regex match.

javascriptjavascript
const text = "Order #12345 confirmed";
 
console.log(text.search(/\d/));
console.log(text.search(/\d+/));

Both print 7 because the first digit appears at position 7. The regex /\d/ matches a single digit, and /\d+/ matches one or more digits, but search only cares about the first match position.

Unlike indexOf, search converts a plain string argument into a regex automatically:

javascriptjavascript
console.log("hello".search("ll"));
console.log("hello".indexOf("ll"));

Both print 2. But search treats "ll" as the regex /ll/, which means special regex characters like the period and asterisk work differently than you might expect. Stick to plain strings with indexOf unless you intentionally want regex behavior.

For a broader overview of all string search and extraction methods, see the JavaScript string methods guide.

When to use which

MethodBest for
indexOfFind position of first plain-text match
lastIndexOfFind position of last plain-text match
searchFind position of first regex pattern match
includesBoolean check: does the string contain this?

The most common real-world pattern is using indexOf to check if a string contains something, then using the returned position to extract or manipulate the surrounding text.

Common mistakes

Treating indexOf as a boolean is the most frequent error. The value 0 is a valid position but falsy in JavaScript, so if (str.indexOf("H")) silently fails when the match is at the start. Always write if (str.indexOf("H") !== -1).

Expecting search to handle a plain string the same as indexOf can cause subtle bugs. The call "file.txt".search(".") returns 0, not 4, because . in a regex matches any character. Use indexOf for plain strings.

Forgetting that all three methods are case-sensitive leads to wrong results. The expression "JavaScript".indexOf("java") returns -1. Normalize both sides with toLowerCase when case should not matter.

Rune AI

Rune AI

Key Insights

  • indexOf returns the position of the first match, or -1 if not found.
  • lastIndexOf returns the position of the last match, searching from the end.
  • search works like indexOf but accepts a regular expression instead of a plain string.
  • Always compare results to -1 explicitly. Do not treat the return value as a boolean.
  • Use includes() instead when you only need a true or false answer.
RunePowered by Rune AI

Frequently Asked Questions

What does indexOf return when nothing is found?

It returns -1. Always compare the result to -1 rather than treating it as a boolean, because indexOf can return 0 for a match at the first position, and 0 is falsy in JavaScript.

Is indexOf case-sensitive?

Yes. 'Hello'.indexOf('hello') returns -1 because the cases do not match. Normalize both strings with toLowerCase() if you need case-insensitive search.

Can I use indexOf to check if a substring exists?

Yes, but includes() is more readable for boolean checks. Use indexOf when you need the exact position, and includes when you just need a yes or no answer.

Conclusion

indexOf, lastIndexOf, and search are the three methods for finding substring positions in JavaScript. Use indexOf for the first occurrence, lastIndexOf for the last occurrence, and search when you need regex pattern matching. All three return -1 when no match is found, and all are case-sensitive.