Javascript Reference - JavaScript String indexOf() Method








indexOf() searches a string and return the position. indexOf() returns -1 if the substring isn't found.

indexOf() method does the search at the beginning.

The indexOf() method is case sensitive.

To search sub string from the end of a string, use the lastIndexOf() method.

Browser Support

indexOf() Yes Yes Yes Yes Yes

Syntax

stringObject.indexOf(searchvalue, start);

Parameter Values

Parameter Description
searchvalue Required. The string to search for
start Optional. Default 0. Where to start the search




Return Value

Return the found index, or -1 if not found.

Example


var stringValue = "hello world"; 
console.log(stringValue.indexOf("o")); //4 

The code above generates the following result.

Search from the middle

An optional second argument tells where to start with.


var stringValue = "hello world"; 
console.log(stringValue.indexOf("o", 6)); //7 

The code above generates the following result.

Find all occurrences

The following code uses while loop to check the return result. If the result is not -1 it will keep searching.


var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"; 
var positions = new Array(); 
var pos = stringValue.indexOf("e"); 
        //from  w w  w.  j av a 2s .  co  m
while(pos > -1){ 
   positions.push(pos); 
   pos = stringValue.indexOf("o", pos + 1); 
} 
console.log(positions); //3,13,15,29

The code above generates the following result.





Example 2

The following code shows how to use indexOf to validate an email address.


//from w w  w.  j  a v  a 2  s  .c  o m
var email_add="yourName@yourserver.com";
if (email_add.indexOf("@") == -1)
{
    console.log("You need an '@' symbol in your address, please try again.");
}
if (email_add.indexOf(".") == -1)
{
    console.log("You need a '.' symbol in your address, please try again.");
}
if ( (email_add.indexOf("@") != -1) && (email_add.indexOf(".") != -1) )
{
    console.log("Thanks!");
}

The code above generates the following result.