Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: indexOf vs. Match when Searching Strings?

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-/) 
like image 222
indra Avatar asked Jan 21 '11 09:01

indra


People also ask

Is JavaScript regex faster than indexOf?

IndexOf is only useful for checking the existence of an exact substring, but Regex is much more powerful and allows you to do so much more.

Is indexOf faster than regex?

For just finding a keyword the IndexOf method is faster than using a regular expression. Regular expressions are powerful, but their power lies in flexibility, not raw speed. They don't beat string methods at simple string operations.

Why do we use indexOf in JavaScript?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.


2 Answers

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?

like image 123
David Tang Avatar answered Sep 20 '22 03:09

David Tang


Your comparison may not be entirely fair. indexOf is used with plain strings and is therefore very fast; match takes a regular expression - of course it may be slower in comparison, but if you want to do a regex match, you won't get far with indexOf. On the other hand, regular expression engines can be optimized, and have been improving in performance in the last years.

In your case, where you're looking for a verbatim string, indexOf should be sufficient. There is still one application for regexes, though: If you need to match entire words and want to avoid matching substrings, then regular expressions give you "word boundary anchors". For example:

indexOf('bar') 

will find bar three times in bar, fubar, barmy, whereas

match(/\bbar\b/) 

will only match bar when it is not part of a longer word.

As you can see in the comments, some comparisons have been done that show that a regex may be faster than indexOf - if it's performance-critical, you may need to profile your code.

like image 30
Tim Pietzcker Avatar answered Sep 19 '22 03:09

Tim Pietzcker