In the Chrome or Firebug console:
reg = /ab/g
str = "abc"
reg.exec(str)
==> ["ab"]
reg.exec(str)
==> null
reg.exec(str)
==> ["ab"]
reg.exec(str)
==> null
Is exec somehow stateful and depends on what it returned the previous time? Or is this just a bug? I can’t get it to happen all the time. For example, if ‘str’ above were “abc abc” it doesn’t happen.
A JavaScript
RegExpobject is stateful.When the regex is global, if you call a method on the same regex object, it will start from the index past the end of the last match.
When no more matches are found, the index is reset to
0automatically.To reset it manually, set the
lastIndexproperty.This can be a very useful feature. You can start the evaluation at any point in the string if desired, or if in a loop, you can stop it after a desired number of matches.
Here’s a demonstration of a typical approach to using the regex in a loop. It takes advantage of the fact that
execreturnsnullwhen there are no more matches by performing the assignment as the loop condition.DEMO: http://jsfiddle.net/pPW8Y/
If you don’t like the placement of the assignment, the loop can be reworked, like this for example…
DEMO: http://jsfiddle.net/pPW8Y/1/