How to use String indexOf() to search a sub string in Javascript

Description

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.

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 2  s  .c  om*/
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.


/*w  w w  .  ja va  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.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window