search

String.prototype.indexOf

Returns the index of the first occurrence of searchValue within the string, or -1 if not found. Search is case-sensitive and starts from fromIndex (default 0).

str.indexOf(searchValue[, fromIndex])

Parameters

Parameter Purpose
searchValue Substring to locate (coerced to string)
fromIndex Zero-based index to start searching (default 0)

Examples

console.log('hello world'.indexOf('world'));

Prints 6

console.log('abcabc'.indexOf('b', 2));

Prints 4

console.log('hello'.indexOf('Z'));

Prints -1

console.log('Hello'.indexOf('hello'));

Prints -1 (case-sensitive)

Gotcha

Returns -1 when not found, so use === -1 checks or prefer includes() for boolean tests. Case-sensitive with no locale awareness.

Related methods

← All JS string methods · JS array methods