When you use the global flag, the regex becomes "sticky." That is to say, it uses a counter variable to track where the last match was found. Rather than matching from the beginning each time, a sticky regex will actually pick up where the last match ended. This counter will only reset back to 0 (the beginning) if the entire match fails (which is why it works every-other-time)
In your case, my suggestion would be to drop the g
flag.
For more information: RegExp @ MDC