Odd RegExp.test()

This is small, most likelly well known item related to JavaScript RegExp.prototype.test(). Who worked with it – knows, but for people who tried to use intition and logic, IT WILL not work 🙂



Let’s imagine we have such pattern, and want to test our strings with it.


And here is piece of code (WORKING)

if ( /^(FOO_BAR|BAZ)$/g.test(myStr) ) { // then do something }

Quite intuitive – you have your string, you have pattern, and you test your string against pattern to have true/false.

BUT. Let’s imagine, you have many places to use this pattern, and to follow DRY you wnat to use variable.

var PATTERN = /^(FOO_BAR|BAZ)$/g;

And one of code can be like this:

if ( PATTERN.test(myStr) {
    // then do something


And here is why  – OFFICIAL text from JavaScript MDN:

As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

No idea how it works behind the code on polyfil level, but I was using logic, and I failed.

My solution was creation dedicated function, and calling that function as many times I need.

function checkMyString(str){
   return /^(FOO_BAR|BAZ)$/g.test(str);

So in this case, pattern is in one place (DRY is OK) and no matter how many times you call function it wall do .test() always new.

PS. Another solution her emight be usage String.prototype.search() of myStr.search(PATTERN). But it requires another way of condition logic.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s