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
String.prototype.includes
Returns true if searchString appears anywhere in the string, otherwise false. Added in ES2015 as a cleaner boolean alternative to indexOf() !== -1.
String.prototype.startsWith
Returns true if the string begins with searchString at the given position (default 0). Added in ES2015 and is more efficient than slice() + === comparisons.
String.prototype.match
Runs a regular expression against the string and returns match information. With the g flag it returns an array of all match strings; without it, an exec-style array with capture groups, index, and input (or null).
String.prototype.endsWith
Returns true if the string ends with searchString when considered up to endPosition (default str.length). Useful for file extension and suffix checks.
String.prototype.matchAll
Returns an iterator of all detailed match results, each including capture groups, index, and input. Added in ES2020 and requires a global (g) RegExp — non-global patterns throw TypeError.