A simple test script:
<script type="text/javascript"> var reg = new RegExp('#([a-f0-9]{3})$', 'gi'); for (var i = 0; i < 10; i++) { console.log(reg.exec('#fff')); } </script>
Console output:
["#fff", "fff"] null ["#fff", "fff"] null ["#fff", "fff"] null ["#fff", "fff"] null ["#fff", "fff"] null
Why is every other result null when the input remains constant?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With