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

Posted by nw on Stack Overflow See other posts from Stack Overflow or by nw
Published on 2010-04-19T18:29:29Z Indexed on 2010/04/19 18:33 UTC
Read the original article Hit count: 225

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about regex

Related posts about JavaScript