JavaScript String indexOf()
Example
Search a string for "welcome":
let str = "Hello world, welcome to the universe.";
str.indexOf("welcome") // Returns 13
str.indexOf("Welcome") // Returns -1
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The indexOf() method returns the position of the first occurrence
of a specified value in a string.
indexOf() returns -1 if the value is not found.
indexOf() is case sensitive.
Tip: Also look at the
lastIndexOf() method.
Browser Support
indexOf() is fully supported in all browsers:
| Chrome | IE | Edge | Firefox | Safari | Opera |
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
string.indexOf(searchvalue, start)
Parameter Values
| Parameter | Description |
|---|---|
| searchvalue | Required. The string to search for |
| start | Optional. Default 0. At which position to start the search |
Technical Details
| Return Value: | A Number, representing the position where the searchvalue occurs for the first time, or -1 if it never occurs |
|---|---|
| JavaScript Version: | ECMAScript 1 |
More Examples
Example
Find the first occurrence of the letter "e" in a string:
let str = "Hello world, welcome to the universe.";
str.indexOf("e") // Returns 1
Try it Yourself »
Example
Find the first occurrence of the letter "e" in a string, starting the search at position 5:
let str = "Hello world, welcome to the universe.";
str.indexOf("e", 5) // Returns 14
Try it Yourself »

