Coder Perfect

To see if a string matches a regular expression, use regex.test instead of string.match.


I frequently use the string match function to determine whether a string matches a regular expression.


Is there a distinction between these two:

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

They appear to provide the same outcome?

Asked by gdoron is supporting Monica

Solution #1

Let’s have a look at what each function does first:

regexObject.test( String )

string.match( RegExp )

Due to the fact that null evaluates to false,

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

Is there a distinction in terms of performance?

Yes. I came across this brief note on the MDN website:

Is there a major difference?

Yes, yes, yes, yes, yes, yes, yes, yes, yes, yes, yes, yes, yes According to this jsPerf I put up, the difference is between 30% and 60% depending on the browser:

If you need a quick boolean check, use.test. When using the g global flag, use.match to return all matches.

Answered by gdoron is supporting Monica

Solution #2

Remember to take the global flag into account 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 when a new match is found, Regexp keeps track of the lastIndex.

Answered by gtournie

Post is based on