I get this behavior in both Chrome (Developer Tools) and Firefox (Firebug). Note the regex test returns alternating true/false values:
> var re = /.*?\bbl.*\bgr.*/gi;
undefined
> re
/.*?\\bbl.*\\bgr.*/gi
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false
However, testing the same regex as a literal:
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
I can't explain this and it's making debugging very difficult. Can anyone explain this behavior?
I get this behavior in both Chrome (Developer Tools) and Firefox (Firebug). Note the regex test returns alternating true/false values:
> var re = /.*?\bbl.*\bgr.*/gi;
undefined
> re
/.*?\\bbl.*\\bgr.*/gi
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false
> re.test("Blue-Green");
true
> re.test("Blue-Green");
false
However, testing the same regex as a literal:
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
> /.*?\bbl.*\bgr.*/gi.test("Blue-Green");
true
I can't explain this and it's making debugging very difficult. Can anyone explain this behavior?
Share Improve this question edited May 27, 2010 at 0:11 Earlz 64k100 gold badges313 silver badges507 bronze badges asked Apr 19, 2010 at 18:29 nw.nw. 2,2266 gold badges31 silver badges42 bronze badges 4- Funky. Reproduced w/ Firefox 3.5.8 and Firebug 1.5.3. Still occurs if "Blue-Green" is stored into a variable and re-used. – Darien Commented Apr 19, 2010 at 18:34
-
I found this to be mildly amusing. Instead of using
a = !a
to switch between true/false, why don't we define a private regexp object and useregexp.test!
– Warty Commented Apr 19, 2010 at 18:35 - It's defined in the ECMAScript spec to behave like this, it'll be the same in all browsers. – bobince Commented Apr 19, 2010 at 18:38
- Stops if you don't use /g Edit: Ah, answer says why ;) – Darien Commented Apr 19, 2010 at 18:39
1 Answer
Reset to default 11/g
(global) regexps will do that, yes.
See this question.
When you write a literal, you're getting a new regexp object every time, so losing the lastIndex
state associated with the old object.