RegEx.test() returns alternating results

Nikhil John
2 min readSep 26, 2018

--

Javascript — the truly weird parts

An Excellent Source of RegEx knowhow

Now I’m a little embarrassed to have just run into this issue for the first time after 8 years of Javascript coding. That is probably because I haven’t used a lot of Regular Expressions in my code. This could be a good thing even, considering how often RegExes (or RegExs ? ) are abused as shortcuts in place of good logic.

One issue that I just ran into was that my RegEx was returning alternating results for the exact same expression. See below

This was truly bizarre! Shouldn’t the RegEx always return the same result for a given string and condition? Apparently not.

See below the caveat from MDN regarding this behavior:

Using test() on a regex with the global flag

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property). It is worth noting that the lastIndex will not reset when testing a different string.

So remember, if you’re looking for only single matches, do not use the /g flag at the end of your RegEx or your code will have unpredictable results

Happy coding!

--

--

Nikhil John

Tips and tricks on Travelling and Web Engineering! Senior Engineer @Microsoft