JavaScript String indexOf Explained Step by Step
String indexOf() returns where a substring first appears, or -1. See the position argument, empty strings, code unit indexes and the truthiness trap.

indexOf() on a string returns one number that carries two meanings: a position when the text is found and -1 when it is not. The first position in a string is 0, which is falsy, and the miss value -1 is truthy, so if (path.indexOf("/api")) is true for every path that does not contain /api and false for every path that starts with it. That is the whole reason this method needs a careful read, even though it has been in the language since the first edition. This post covers what it takes and returns, how the optional start position behaves, what happens with empty and non-string arguments, and why the index you get back counts UTF-16 code units and not characters. Everything runs on Node.js 24. If you only need a yes or no, [the post on String.prototype.includes()](/library/javascript-string-includes) gives you a boolean that cannot be misread.
What indexOf() takes and returns
The signature is string.indexOf(searchString, position). It looks for the first occurrence of searchString that begins at or after position, and returns the index where that occurrence starts. If there is none, it returns -1.
| Argument | Meaning | Default |
|---|---|---|
searchString | The text to look for. A non-string is converted to a string | "undefined" when omitted |
position | The index to begin scanning from | 0 |
The method never changes the string, because strings are immutable, and its result is always an integer from -1 up to the string length. The match is exact and case sensitive.
const word = "Mississippi";
console.log(word.indexOf("ss"));
console.log(word.indexOf("ss", 3));
console.log(word.indexOf("ss", 6));
console.log(word.indexOf("SS"));2
5
-1
-1The letters of "Mississippi" sit at M(0) i(1) s(2) s(3) i(4) s(5) s(6) i(7) p(8) p(9) i(10). The first ss begins at 2. Starting the scan at 3 skips it, because the match would have to begin at or after 3, and finds the second pair at 5. Starting at 6 leaves only sippi, which has no pair. The uppercase search fails because S and s are different code units.
Finding every occurrence
The method returns only the first match, so you move position forward past each hit to collect all of them. The step must be at least one, and stepping by the length of the search text is also fine when you do not want overlapping matches.
const text = "Mississippi";
const found = [];
let at = text.indexOf("i");
while (at !== -1) {
found.push(at);
at = text.indexOf("i", at + 1);
}
console.log(found);[ 1, 4, 7, 10 ]The explicit !== -1 is the safe habit. When you step by one, overlapping matches are reported: searching "aaaa" for "aa" this way gives 0, 1 and 2. If you want the matches as objects with their groups, [matchAll()](/library/javascript-string-matchall) does the walking for you, but it needs a regular expression with the g flag.
Empty strings and the position clamp
An empty search string matches at the starting position, after that position has been clamped into the range from 0 to the length of the string. A position below zero or NaN acts as 0, and one above the length acts as the length.
console.log("abc".indexOf(""));
console.log("abc".indexOf("", 2));
console.log("abc".indexOf("", 99));
console.log("abc".indexOf("c", -50));
console.log("abc".indexOf("c", 99));0
2
3
2
-1The empty string is found at the clamped position, so asking for it from 99 returns 3, the length. That result is not an index of any character, and it is a frequent source of off-by-one surprises when the search term comes from user input that may be blank. If a blank term should mean "no match", test for it before calling.
A negative position does not count from the end, which differs from slice(). It clamps to 0, and the scan still runs forward.
Arguments that are not strings
Anything you pass as searchString is converted with the usual string conversion. Numbers become their decimal text, arrays become comma-joined text, and a missing argument becomes the text "undefined".
console.log("a1b2".indexOf(2));
console.log("x".indexOf());
console.log("undefined!".indexOf());
console.log("see /b/ here".indexOf(/b/));3
-1
0
4The last line shows a difference from includes(). The indexOf() method does not reject a regular expression. It converts it to its source text, "/b/", and looks for that literal text, finding it at index 4. A pattern is never applied. That silent conversion is a trap when a refactor swaps a string for a regex and the code keeps running with a wrong answer. If you want a pattern, use [match()](/library/javascript-string-match) or RegExp.prototype.exec(), which report where the pattern matched.
Indexes count code units
Strings in JavaScript are sequences of UTF-16 code units, and indexOf() reports positions in those units. Most text is one unit per character. Characters outside the Basic Multilingual Plane, including most emoji, use two units, so every index after one shifts by two.
const line = "\u{1F600}a";
console.log(line.length);
console.log(line.indexOf("a"));
console.log([...line].length);
console.log([...line].indexOf("a"));3
2
2
1The emoji occupies indexes 0 and 1, so the letter is at 2. Spreading the string iterates by code point and produces two elements, where the letter is at index 1. Both answers are right for their own definition, and mixing them is the bug. If you take an index from indexOf() and use it with slice(), substring() or at(), you stay in code units and everything lines up. If you take it and use it as an index into a spread array, it is off by one for each emoji before it.
Accents have the same trap in another form. A letter with an accent can be a single code point or a base letter plus a combining mark, and indexOf("e") finds the base letter inside the second form only. Call [normalize()](/library/javascript-string-normalize) on both sides before searching if the text comes from sources you do not control.
Slicing around a match
A common job for indexOf() is splitting a string at a delimiter without allocating an array. You find the position, then cut on either side of it.
const email = "[email protected]";
const at = email.indexOf("@");
console.log(email.slice(0, at));
console.log(email.slice(at + 1));
console.log(at);ana
example.com
3The delimiter has length one, which is why the second cut adds 1. For a longer delimiter, add its length. This pattern is quick and has no regular expression, which makes it a good fit for a single delimiter in a trusted format. The danger is the miss case.
A mistake we hit: the truthiness test and the unchecked miss
The first failure is treating the result as a boolean.
const hit = "/api/users";
const miss = "/home";
console.log(hit.indexOf("/api") ? "is api" : "not api");
console.log(miss.indexOf("/api") ? "is api" : "not api");not api
is apiBoth answers are inverted. The path that starts with /api returns 0, which is falsy, and the path that does not contain it returns -1, which is truthy. The fix is to compare explicitly with !== -1, or to use includes() for a membership test and startsWith() when the position must be the start.
The second failure is slicing without checking for a miss.
const bad = "nope";
const i = bad.indexOf("@");
console.log(bad.slice(0, i));
console.log(i);nop
-1slice(0, -1) is a legal call that means "everything but the last character", so a missing delimiter produces a plausible wrong value, "nop", and no error. This kind of bug passes tests that only use valid input. Guard with if (i === -1) and decide explicitly what a missing delimiter means for your data.
Choosing between indexOf and its neighbors
| You want | Use | Returns |
|---|---|---|
| A yes or no for a substring | includes() | true or false |
| The first position of a substring | indexOf() | index or -1 |
| The last position of a substring | lastIndexOf() | index or -1 |
| Whether a prefix matches | startsWith() | true or false |
| The position of a pattern match | RegExp.prototype.exec() | match object or null |
| Every match of a pattern | matchAll() | iterator of match objects |
We use indexOf() when the position is the point: to slice, to cut, or to continue scanning from a known place. When the position is not used, includes() states the intent better, and a reader does not have to wonder whether -1 is handled. The array method of the same name has a different comparison rule and works on elements, not substrings, as described in [the post on Array.prototype.indexOf()](/library/javascript-array-indexof). For example, ["abc"].indexOf("b") is -1, because the element "abc" is not equal to "b", while "abc".indexOf("b") is 1.
Where indexOf stops being the right tool
The method matches literal text only. It cannot ignore case, cannot match a word boundary, and cannot match alternatives. Looking for "cat" inside "concatenate" succeeds at index 3 even when you meant the word. A word-boundary pattern in a regular expression is the right tool there. For case-insensitive matching, lowercasing both sides works for plain identifiers, though locale-specific rules can still bite in user-facing text.
It is also the wrong tool for structured values. Finding a query string with url.indexOf("?") is fine for a quick cut, but parsing a full URL, a CSV line with quoted delimiters, or a path with encoded characters needs a real parser. A delimiter inside quotes will fool indexOf() every time.
For heavy repeated scanning of a large text, such as finding thousands of terms, each call restarts a scan, so the work grows with the text size and the number of terms. A single pass with a compiled regular expression, or a tokenizer that splits once and looks tokens up in a Set, avoids the repeated scans. For ordinary short strings none of that matters, and we would not add machinery for it.
The method is defined in the ECMAScript specification as String.prototype.indexOf, and MDN documents it on the String.prototype.indexOf page. For how strings are indexed in code units, read the MDN String reference.


