String.prototype.indexOf()
Returns the index of the first occurrence of a substring, or -1 if absent.
Syntax
str.indexOf(searchString, position) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
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
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |