String Searching in Javascript

New Javascript developers frequently ask how to search for a string within another string using Javascript. The indexOf method is what you are looking for and is available on String and Array objects. String.indexOf(searchValue) returns the index of (hence the name) the first match OR -1 if the value was not found, it does not return false and a common gotcha is false positives from code like the following:

<code>var myString = "the quick brown fox jumps over the lazy dog";
var searchValue = "the";
if(myString.indexOf(searchValue)){ 
   // even though it matched, this will not get executed because the index of "the" is 0 
}</code>

You must explicitly check that the return value is or isn’t -1:

<code>var myString = "the quick brown fox jumps over the lazy dog";
var searchValue = "the";
if(myString.indexOf(searchValue) !== -1){ 
   // this will get executed
}</code>

Here is a more complex string search I wrote over on bootsnipp.com that utilizes simple string searches for filtering tables. The javascript for it is inlined here:

P.S. Even though the title of the article is string searching, as I stated above indexOf also works on Array objects:

<code>var arr = ['the', 'quick', 'brown', 'fox'];
var search = 'quick';
console.log(arr.indexOf(search)); // will output 1 as "quick" is in index 1 of the array</code>

Leave a Reply