Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
"banana".indexOf("an"); // 1

Try it

JS Finding positions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Counting matches and splitting at a separator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 returns 0, which is falsy, so if (text.indexOf("x")) is a bug. Write !== -1 or use includes().
  • Case-sensitive. Lower-case both strings first if case should not matter.
  • Only the first match is returned. Loop with the position argument (as in the second example) to find them all, or use matchAll() for patterns.
  • Empty search text returns the position itself, clamped to the string length: "banana".indexOf("", 10) is 6.
  • 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. Use search() to get the index of a pattern match.
  • Arrays have their own indexOf(), which compares whole elements using strict equality. See Array.prototype.indexOf().

Browser support

indexOf() works in every browser, old and new.