I know there are a few regex/lastIndex
discrepancies but this one is new to me!
Expected behaviour: Creating a new regular expression (with literal/constructor) will, obviously, create a new RegExp object with a lastIndex
property set to zero.
Actual behaviour: (in FF, Chrome): The lastIndex property seems to persist through multiple RegExp creations.
E.g.
function foo(s) {
// A *NEW* regular expression
// is created on each call of foo():
var regex = /ABC/g;
document.write( regex.lastIndex + '<br/>' );
// regex.test() updates lastIndex property
regex.test(s);
// This is where the regex's life should end...
// (Why does it persist?)
}
foo('ABC');
foo('ABCABC');
foo('ABCABCABC');
See here: http://jsbin.com/otoze
A new RegExp object is being created on every function call (right?), so why is the following being written to the document?? -
0
3
6
???
Note, this weirdness appears to happen in FF(3) and Chrome(2), but, curiously not IE.
Is this expected behaviour, does IE get it wrong or right? Is this a well-known bug?
EDIT: this doesn't appear to happen when instantiating the regex with a constructor instead of a literal. E.g. new RegExp('ABC','g');
... Still, the literal should (theoretically) work, right?