JavaScript Reference ยท String
String.prototype.indexOf()
Reference for JavaScript String.prototype.indexOf(): find the first index of a substring, use the start position, count matches and avoid the falsy 0 trap.
The indexOf() method searches a string for some text and returns the index where the first match begins. If the text is not found, it returns -1.
It is the tool to use when you need the position, for example to cut a string at a separator. When you only need a yes-or-no answer, includes() reads better.
"banana".indexOf("an"); // 1
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.indexOf(searchString) string.indexOf(searchString, position)
| Name | Description |
|---|---|
searchString |
The text to look for. It is converted to a string; undefined becomes "undefined". |
position |
Optional. The index to start searching from. Defaults to 0. Negative values and NaN count as 0; values above the length are clamped to the length. |
Return value: the index of the first match at or after position, or -1 if there is none.
Exceptions: none. Unlike includes(), a regular expression argument does not throw; it is converted to a string and searched literally.
Usage notes
- Always compare with
-1. A match at the very start returns0, which is falsy, soif (text.indexOf("x"))is a bug. Write!== -1or useincludes(). - Case-sensitive. Lower-case both strings first if case should not matter.
- Only the first match is returned. Loop with the
positionargument (as in the second example) to find them all, or usematchAll()for patterns. - Empty search text returns the
positionitself, clamped to the string length:"banana".indexOf("", 10)is6. - Index units: the result counts UTF-16 code units, so text after an emoji is offset by two per emoji.
- To search from the end, use
lastIndexOf(). - Patterns:
indexOf()cannot take a regular expression meaningfully. Usesearch()to get the index of a pattern match. - Arrays have their own
indexOf(), which compares whole elements using strict equality. SeeArray.prototype.indexOf().
Browser support
indexOf() works in every browser, old and new.