JavaScriptStrings

String.prototype.indexOf()

Returns the index of the first occurrence of the given text in a string, or -1 when it is not there.

Returns
The index of the first occurrence (counted from 0), or -1 when the text was not found.
Changes the original
No
On this page

Example

#
JavaScript
const text = 'Learn HTML, then CSS, then JavaScript'

console.log(text.indexOf('HTML'))
console.log(text.indexOf('then'))
console.log(text.lastIndexOf('then'))
console.log(text.indexOf('Python'))
Console
6
12
22
-1

Definition and usage

#

The indexOf() method looks for a piece of text and returns the position of its first character. Indexes start at 0. When the text is not found in the string, the result is -1, so compare the result against -1 instead of treating it as a boolean.

The second argument sets the index where the search starts, which lets you find successive occurrences in a loop. The sibling method lastIndexOf() searches the text from the end and returns the position of the last occurrence.

When you only need a yes-or-no answer, includes() is more readable. indexOf() comes in handy when you need the position for something else, such as cutting out a piece with slice().

Syntax

#
Syntax
string.indexOf(searchString)
string.indexOf(searchString, position)
string.lastIndexOf(searchString)

Parameters

#
  • searchString

    string

    The text to search for. Letter case matters.
  • position

    number, optional

    The index where the search starts. Defaults to 0.

More examples

#
Trap: checking the result in an if
JavaScript
const title = 'JavaScript'

if (title.indexOf('Java')) {
  console.log('Found')
} else {
  console.log('Not found')
}

console.log(title.indexOf('Java') !== -1)
Console
Not found
true

indexOf() returned 0, and zero is falsy, so the condition fell into the else branch. Always compare the result against -1, or use includes().

Counting occurrences in a loop
JavaScript
const log = 'ok, error, ok, ok, error'
let count = 0
let position = log.indexOf('error')

while (position !== -1) {
  count++
  position = log.indexOf('error', position + 1)
}

console.log(count)
Console
2
Slicing based on a position
JavaScript
const email = 'mia@example.com'
const at = email.indexOf('@')

console.log(email.slice(0, at))
console.log(email.slice(at + 1))
Console
mia
example.com

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Never check the result with if (text.indexOf(x)). A match found right at the start gives 0, which is falsy. Compare against -1 instead.
  • The method is case-sensitive. To search without case sensitivity, lowercase both strings first.

Related entries

#

Spotted a mistake or missing an example? Write to us.