JavaScript (ES2026) reference · String Methods
JavaScript String indexOf() Method
Return the index of the first occurrence of some text, or -1 if it isn't found.
JavaScript (ES2026) Since ES1
Syntax
string.indexOf(searchString, position)
Parameters
| Parameter | Description |
|---|---|
searchString |
Text to look for. |
position optional |
Index to start from. Default: 0 |
Return value
An index, or -1.
Examples
const s = "banana";
console.log(s.indexOf("an"), s.indexOf("an", 2), s.indexOf("x"));
Output
1 3 -1
const email = "[email protected]";
const at = email.indexOf("@");
console.log(email.slice(0, at), email.slice(at + 1));
Output
ada example.com
Version history
| Version | Change |
|---|---|
| JavaScript ES1 | Added |
In other languages
str.find()· Pythonstrpos()· PHPmb_strpos()· PHP
Related
string.lastIndexOf()· Return the index of the last occurrence of some text, searching backwards, or -1 if it isn't found.string.includes()· Return true if the string contains the given text anywhere. Case-sensitive.string.search()· Return the index of the first regular-expression match, or -1 if there is none.- JavaScript Strings · tutorial
- JavaScript String Methods · tutorial