Reputation: 2226
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?
Upvotes: 5
Views: 1460
Reputation: 536755
/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.
Upvotes: 11