The lastIndex property is set to point at the character following the previous match. This allows you to build an iterator that cycles according to the matches for the search pattern within the source string.
When a null result is returned from the RegExp.exec() method, this value is set to 0.
The RegExp.exec() method uses the lastIndex property as its starting point for the next search. This means that if you prematurely exit the pattern searching iterator, you should also manually set this value to 0 as well. This will allow the same RegExp object to be used with another pattern (or the same one) to search a different string.
The lastIndex property will be reset to 0 when the regular expression is called by String.search(), String.replace() and String.match().
The lastIndex behaviour is only appropriate when the g attribute is applied to the pattern that searches the target string. It is of no consequence in a non-global pattern match.