JavaScript Regex Global Flag

Posted on

This doesn’t apply in all cases, but in my experience:

  • Use the global flag when matching regular expressions in a string.
  • Do not use the global flag when testing.

I’ll use this as my example:

var example = 'The tale of mats and bats';
var regex = /.ats/;
var regex_global = /.ats/g;

Matching will by default return the first matched result.

> ["mats"]

Typically I want all of the results returned in a neat array, so the global flag is helpful.

> ["mats", "bats"]

When testing for a regular expression, the non-global regex works great.

> true

However, when I try to use the global one, I get inconsistent results.

> true
> true
> false

This is because when test is called with a global regex, it saves the position of the last matched string and starts from that position the next time it’s called. Since there are two matches in my example, true is returned the first two times. However, the third time it is called, it only tests against the last portion of my example string after the second match, so it fails.

Leave a Reply

Your email address will not be published.