Thursday, April 11, 2013

JavaScript search() != indexOf() Method

Quite frequently we need to find a specific word from a large chunk of string. With more focus on web development and the advancement of client-side scripting capability, more efforts have to focus on javascript nowadays.

I came across with this and bump into these 2 methods, both methods look identical (almost) to me to achieve what I was looking for.
  • search()
  • indexOf()
I thought they can achieve the same result, but eventually they aren't.

First, let's use the search() to perform some testing.
Test 1: Using the w3schools's Tryit Editor with default function to search "W3Schools":

function myFunction()
{
var str="Visit W3Schools!"; 
var n=str.search("W3Schools");
document.getElementById("demo").innerHTML=n;
}

You'll get result:
6 (which is correct)

Test 2: then use another method indexOf() on the same function to search same string [MUST click "Submit Code" after change in "Tryit Editor"]:

function myFunction()
{
var str="Visit W3Schools!"; 
var n=str.indexOf("W3Schools");
document.getElementById("demo").innerHTML=n;
}

You'll get result:
6 (which is correct too)

Nothing fancy, nothing wrong.
OK, what about change the string to search from "W3Schools" to "W3|Schools" (adding a "|" character, since it's frequently used as a delimiter)

Test 3: if using search() method [MUST click "Submit Code" after change in "Tryit Editor"]:

function myFunction()
{
var str="Visit W3Schools!"; 
var n=str.search("W3|Schools");
document.getElementById("demo").innerHTML=n;
}

You'll get result:
6 (which is wrong)

Test 4: if using indexOf() method [MUST click "Submit Code" after change in "Tryit Editor"]:

function myFunction()
{
var str="Visit W3Schools!"; 
var n=str.indexOf("W3|Schools");
document.getElementById("demo").innerHTML=n;
}

You'll get result:
-1 (which is still correct)

From Test 3 & Test 4, you get different result if the string your search contains special character "|". Looking back, I was overlooked by its definition (see fonts in read).

search() Method:
The search() method searches a string for a specified value, or regular expression, and returns the position of the match.
This method returns -1 if no match is found.

indexOf() Method:
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.

Looks like special character "|" has caused some effect on the regular expression and need special treatment on it. Lesson learnt.