373

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?

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 4
    these are the best tests you will find http://jsperf.com/regexp-test-vs-match-m5 – ajax333221 Jun 07 '12 at 22:13
  • @ajax333221. Thanks for the jsperf, but I'm not sure it's a good one. The regex match using a match group, which isn't needed when looking a boolean value. – gdoron Jun 08 '12 at 07:28
  • "Does a string match a presented pattern?" vs "Does my pattern match a presented string?". `str.match(/{regex}/)` seems more logical to read than `/{regex}/.test(str)`. Maybe next-gen javascript should include a `str.like(/{regex}/)` that behaves like test but reads like match. – PotatoFarmer Nov 20 '22 at 23:23

2 Answers2

559

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 7
    Not too surprised since the string function needs to flip things around and then create the Array if there's a match. Looks like I'll keep using `.test()`. :) –  Jun 07 '12 at 22:30
  • what about a perf for actually extracting the value....also why not throw a 3rd case in for .exec(). –  Apr 07 '13 at 20:20
  • @livingston_mechanical, because it wasn't the subject of the post. – gdoron Apr 07 '13 at 20:40
  • 35
    My two cents: performance is overrated. Either option can do ~15,000 operations in the flicker of a monitor, so unless you're doing bulk regex client-side, speed isn't relevant. Of course 'test' is logically the correct function if a boolean result is what you're after. Thanks for the Q/A BTW. – David Gilbertson Nov 14 '13 at 21:12
  • What about test() vs. indexOf() – Alex Shilman Jan 26 '14 at 14:49
  • 2
    Interestingly test is 41% slower than match for me using the jsPerf test above (Chrome 41, OSX). – Benjie Apr 13 '15 at 08:31
  • @Benjie Similar result: test is 21% slower than match for me on Chromium 42, OSX (±3% over 4 runs). – SimeonJM Jun 02 '15 at 00:47
  • 1
    @AlexShilman indexOf is faster (but not much) than test according to this http://stackoverflow.com/questions/183496/javascript-style-optimization-string-indexof-v-regex-test (you'd expect it to be faster). – podperson Jul 21 '16 at 20:51
  • .match() didn't work for me for some reason, with the same regex that i used in .test(), maybe a typo, no idea. – Jo Smo Aug 24 '16 at 05:33
  • another performance considerations about searching in strings: http://stackoverflow.com/questions/5296268/fastest-way-to-check-a-string-contain-another-substring-in-javascript – cregox Mar 10 '17 at 08:01
  • 9
    One thing that might bite you here (it bit my team recently): If you use the 'g' flag on your Regex and create a new instance (i.e. via new RegExp(, 'g')) and you reuse that instance, running "test" is stateful, i.e. will return different results when run multiple times. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#Using_test()_on_a_regex_with_the_global_flag for details. – davertron Jul 19 '19 at 14:19
  • @DavidGilbertson - Your remark was worth much more than two cents to me. I was wondering about the practical impact of the performance issue. Thanx for clearing that up! – Frank Conijn - Support Ukraine Aug 24 '19 at 23:57
186

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.

gtournie
  • 4,143
  • 1
  • 21
  • 22
  • 34
    I was just head banging seeing that my regex.test() was randomly logging "true" then "false" then "true"...thanks! – adriendenat Apr 11 '14 at 15:29
  • 15
    I think this is the better answer. It explains that they don't give the same result and that reg.test() has a dangerous pitfall. To me this makes string.match() the clear choice. Performance has never been any issue for me. – James Sep 30 '15 at 15:35
  • 8
    This is important! Going crazy trying to figure out why every other result was missing...for reference of anyone else that finds this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex – Dan Nov 10 '16 at 15:47
  • 3
    If you're as confused as I was, see http://stackoverflow.com/q/1520800/3714913. There's also [String.prototype.search()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search), which returns an index but doesn't have this issue as far as I can tell. – Nateowami Mar 19 '17 at 07:10
  • 3
    Just curious, what's the point of having a global flag for `.test()`? isn't the point of `.test()` to check if the string has a matching regexp? – buhbang Aug 20 '18 at 21:56
  • 1
    regexp.test(...) should never really have the global flag set on the regexp unless you are looking through a bunch of text wanting to count matches. – Troy Morehouse Nov 10 '18 at 07:45
  • 1
    @buhbang when you have a regex and use for multiple purposes. In here you test() a string, in there you split/replace a string or do something else. – Thach Lockevn Sep 30 '21 at 15:19