The JavaScript string.indexOf() method
The indexOf() method returns the index of the first occurrence of a substring, or -1 if it isn't found. "hello".indexOf("l") is 2. When you only need to know whether the text is present, includes() reads more clearly.
Overview
indexOf() finds where a substring first appears, counting from 0, and returns -1 if it's not there at all. That -1 is the value you test against. It's case-sensitive, like its string cousins.
A second argument lets you start the search from a given position, which is the trick for finding the next match after one you've already located — call it in a loop, each time starting just past the last hit. To search from the end backward, there's lastIndexOf().
Since includes() arrived, a lot of indexOf() usage has shifted to it for simple presence checks, because includes() returns a boolean directly. Keep indexOf() for when you actually need the position — for example to slice() the string at that point.
Syntax
const i = str.indexOf(searchString)
const i = str.indexOf(searchString, fromIndex)
Parameters
The string.indexOf() method accepts the following parameters.
| Parameter | Description |
|---|---|
searchString |
The substring to find. Case-sensitive. |
fromIndex |
Optional. The index to start searching from. Defaults to 0. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const email = 'user@example.com';
const at = email.indexOf('@');
const domain = email.slice(at + 1);
document.getElementById('out').textContent =
'@ at index: ' + at + '\n' +
'domain: ' + domain; // @ at index: 4 / domain: example.com
</script>
Best practices
- Test against
-1for "not found" — that's the signal value. - Use
indexOf()when you need the position; use includes() for a yes/no check. - Pass a
fromIndexto find later occurrences in a loop. - Pair it with slice() to cut a string at the match position.
Frequently asked questions
What does indexOf() return if the substring is not found?
-1. So if (str.indexOf("x") === -1) means the substring is absent.What is the difference between indexOf() and includes()?
indexOf() returns the position (or -1); includes() returns a boolean. Use includes() for presence checks.Is string indexOf() case-sensitive?
How do I find the last occurrence of a substring?
lastIndexOf(), which searches from the end of the string backward.