Regex in javascript fails every other time with identical input -
this question has answer here:
a simple test script:
<script type="text/javascript"> var reg = new regexp('#([a-f0-9]{3})$', 'gi'); (var = 0; < 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 every other result null when input remains constant?
when use global flag, regex becomes "sticky." say, uses counter variable track where last match found. rather matching beginning each time, sticky regex pick last match ended. counter reset 0 (the beginning) if entire match fails (which why works every-other-time)
in case, suggestion drop g
flag.
for more information: regexp @ mdc
Comments
Post a Comment