String.prototype.indexOf()

Returns the index of the first occurrence of a substring, or -1 if absent.

Since ES1 Spec ↗

Syntax

str.indexOf(searchString, position)

Parameters

NameTypeRequiredDescription
searchString string Yes The substring to search for.
position number No The index to start searching from. Defaults to 0.

Returns

number — The index of the first match, or -1 if not found.

Examples

console.log('hello world'.indexOf('o'));
Output
4
console.log('hello'.indexOf('z'));
Output
-1

Notes

Case-sensitive. Searching for an empty string returns the start position (or the string length if position exceeds it). Use `includes` for a boolean check.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also