JavaScript String indexOf()
Examples
Search a string for "welcome":
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome");
Try it Yourself »
Search a string for "Welcome":
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("Welcome");
Try it Yourself »
Find the first occurrence of "e":
let text = "Hello world, welcome to the universe.";
text.indexOf("e");
Try it Yourself »
Find the first occurrence of "e", starting at position 5:
let text = "Hello world, welcome to the universe.";
text.indexOf("e", 5);
Try it Yourself »
Find the first occurrence of "a":
let text = "Hello world, welcome to the universe.";
text.indexOf("a");
Try it Yourself »
Description
The indexOf()
method returns the position of the first occurrence of a value in a string.
The indexOf()
method returns -1 if the value is not found.
The indexOf()
method is case sensitive.
Syntax
string.indexOf(searchvalue, start)
Parameters
Parameter | Description |
searchvalue | Required. The string to search for. |
start | Optional. The position to start from (default is 0). |
Return Value
Type | Description |
A number | The first position where the search-value occurs. -1 if it never occurs. |
The Differense Between
String indexOf() and String search()
The indexOf()
method cannot search against a regular expression.
The search()
cannot take a start position argument.
Browser Support
indexOf()
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |