Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex.test V.S. string.match to know if a string matches a regular expression

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?

like image 290
gdoron is supporting Monica Avatar asked Jun 07 '12 21:06

gdoron is supporting Monica


People also ask

Which is faster regex match or RegExp test?

The match() method retrieves the matches when matching a string against a regular expression. Use . test if you want a faster boolean check.

Which method is used to test match in string regex?

The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

What is the function to test the matching of a text in a RegExp object in JavaScript?

test() The test() method executes a search for a match between a regular expression and a specified string.

What method is used to tell whether or not matches the given regular expression?

IsMatch(String, String) Indicates whether the specified regular expression finds a match in the specified input string.


2 Answers

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 vs match | Performance Test

Conclusion

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

like image 113
gdoron is supporting Monica Avatar answered Sep 21 '22 15:09

gdoron is supporting Monica


Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g; !!'abcdefghi'.match(reg); // => true !!'abcdefghi'.match(reg); // => true reg.test('abcdefghi');    // => true reg.test('abcdefghi');    // => false <= 

This is because Regexp keeps track of the lastIndex when a new match is found.

like image 42
gtournie Avatar answered Sep 18 '22 15:09

gtournie