Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in javascript fails every other time with identical input [duplicate]

Tags:

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?

like image 598
T. Stone Avatar asked Feb 09 '11 21:02

T. Stone


Video Answer


1 Answers

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

like image 88
Matt Avatar answered Sep 23 '22 15:09

Matt