nw.
nw.

Reputation: 2226

Regular expression test can't decide between true and false (JavaScript)

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

Answers (1)

bobince
bobince

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

Related Questions