RegEx.test() returns alternating results
Javascript — the truly weird parts
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 flagIf the regex has the global flag set,
test()
will advance thelastIndex
of the regex. A subsequent use oftest()
will start the search at the substring ofstr
specified bylastIndex
(exec()
will also advance thelastIndex
property). It is worth noting that thelastIndex
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!