JavaScript: indexOf vs. Match when Searching Strings?

indra picture indra · Jan 21, 2011 · Viewed 63.6k times · Source

Readability aside, are there any discernable differences (performance perhaps) between using

str.indexOf("src") 

and

str.match(/src/)

I personally prefer match (and regexp) but colleagues seem to go the other way. We were wondering if it mattered ...?

EDIT:

I should have said at the outset that this is for functions that will be doing partial plain-string matching (to pick up identifiers in class attributes for JQuery) rather than full regexp searches with wildcards etc.

class='redBorder DisablesGuiClass-2345-2d73-83hf-8293' 

So it's the difference between:

string.indexOf('DisablesGuiClass-');

and

string.match(/DisablesGuiClass-/)

Answer

David Tang picture David Tang · Jan 21, 2011

RegExp is indeed slower than indexOf (you can see it here), though normally this shouldn't be an issue. With RegExp, you also have to make sure the string is properly escaped, which is an extra thing to think about.

Both of those issues aside, if two tools do exactly what you need them to, why not choose the simpler one?