Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  12] [ 4]  / answers: 1 / hits: 197855  / 12 Years ago, thu, june 7, 2012, 12:00:00

Many times I'm using the string match function to know if a string matches a regular expression.





if(str.match(/{regex}/))


Is there any difference between this:



if (/{regex}/.test(str))


They seem to give the same result?


More From » regex

 Answers
14

Basic Usage


First, let's see what each function does:


regexObject.test( String )



Executes the search for a match between a regular expression and a specified string. Returns true or false.



string.match( RegExp )



Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or null if there are none.



Since null evaluates to false,


if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}



Performance


Is there any difference regarding performance?


Yes. I found this short note in the MDN site:



If you need to know if a string matches a regular expression regexp, use regexp.test(string).



Is the difference significant?


The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:


test


Conclusion


Use .test if you want a faster boolean check. Use .match to retrieve all matches when using the g global flag.


[#85074] Wednesday, June 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristinsonjab

Total Points: 364
Total Questions: 98
Total Answers: 98

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
kristinsonjab questions
Fri, Mar 4, 22, 00:00, 2 Years ago
Fri, Jan 22, 21, 00:00, 3 Years ago
Fri, Aug 14, 20, 00:00, 4 Years ago
;