The indexOf() method returns the position of the first occurrence of a specified value in a string.
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
The indexOf() method is case sensitive.
string.indexOf(searchvalue,start)
Parameter | Require | Description |
---|---|---|
searchvalue | Required. | The string to search for |
start | Optional. | Default 0. At which position to start the search |
A Number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs
Search a string for "welcome":
//locate where in the string a specifed value occurs. var str = "Hello world, welcome to the universe."; var n = str.indexOf("welcome"); console.log(n);// w w w. j ava 2 s . c om //Find the first occurrence of the letter "e" in a string: //locate the first occurance of the letter "e". str = "Hello world, welcome to the universe."; n = str.indexOf("e"); console.log(n);