JavaScript Regex Global Flag
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.
example.match(regex);
> ["mats"]
Typically I want all of the results returned in a neat array, so the global flag is helpful.
example.match(regex_global);
> ["mats", "bats"]
When testing for a regular expression, the non-global regex works great.
regex.test(example);
> true
However, when I try to use the global one, I get inconsistent results.
regex_global.test(example);
> true
regex_global.test(example);
> true
regex_global.test(example);
> 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.