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.
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.
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.
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:
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:
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.
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:
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.
search() -- regex-based search
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.
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:
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
| Method | Best for |
|---|---|
| indexOf | Find position of first plain-text match |
| lastIndexOf | Find position of last plain-text match |
| search | Find position of first regex pattern match |
| includes | Boolean 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
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.
Frequently Asked Questions
What does indexOf return when nothing is found?
Is indexOf case-sensitive?
Can I use indexOf to check if a substring exists?
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.
More in this topic
Is JavaScript Frontend or Backend? Full Guide
JavaScript is both a frontend and backend language. Learn the difference between browser JavaScript and Node.js, what each is used for, and which one you should learn first.
Learn JavaScript Step by Step Tutorial with Real Examples
Follow a hands-on tutorial that teaches JavaScript by building a real interactive page. Write your first variables, functions, and event listeners with examples you can run.
JavaScript Tutorial: Complete Beginner's Guide to Programming in 2025
A structured learning path for absolute beginners. Learn what to study first, how to practice, and which JavaScript concepts matter most when you are starting from zero.