This is a common behavior when you deal with patterns that have the global g
flag, and you use the exec
or test
methods.
In this case the RegExp
object will keep track of the lastIndex
where a match was found, and then on subsequent matches it will start from that lastIndex
instead of starting from 0.
Edit: In response to your comment, why doesn't the RegExp
object being re-created when you call the function again:
This is the behavior described for regular expression literals, let me quote the specification:
§ 7.8.5 - Regular Expression Literals
...
The object is created before evaluation of the containing program or function begins. Evaluation of the literal produces a reference to that object; it does not create a new object.
....
You can make a simple proof by:
function createRe() {
var re = /foo/g;
return re;
}
createRe() === createRe(); // true, it's the same object
You can be sure that is the same object, because "two regular expression literals in a program evaluate to regular expression objects that never compare as ===
to each other even if the two literals' contents are identical", e.g.:
/foo/ === /foo/; // always false...
However this behavior is respected on all browser but not by IE, which initializes a new RegExp object every time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…