String.prototype.indexOf
Finds the position of the first occurrence of a substring.
Available since: ES1
Syntax
str.indexOf(searchString, position)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchString | string | The substring to find. |
| position | number | Optional. The position to start searching from. |
Return value
numberThe position of the match, counting from zero, or `-1` if the substring is not found.
Examples
Position of a match:
console.log('Hello, world'.indexOf('world'));Output:
7When there is no match, -1 is returned:
console.log('Hello, world'.indexOf('JS'));Output:
-1Notes
If you only need to know whether the substring is present, the string's includes() is simpler.
See also
- String.prototype.includes — Checks whether a string contains a given substring.
- String.prototype.slice — Returns part of a string.
- String.prototype.lastIndexOf — Finds the last occurrence of a text in a string.
- String.prototype.search — Returns the position of the first regex match.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.