5

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?

Earlz
  • 62,085
  • 98
  • 303
  • 499
nw.
  • 2,206
  • 5
  • 30
  • 40
  • 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 Apr 19 '10 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 use `regexp.test!` – Warty Apr 19 '10 at 18:35
  • It's defined in the ECMAScript spec to behave like this, it'll be the same in all browsers. – bobince Apr 19 '10 at 18:38
  • Stops if you don't use /g Edit: Ah, answer says why ;) – Darien Apr 19 '10 at 18:39

1 Answers1

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.

Community
  • 1
  • 1
bobince
  • 528,062
  • 107
  • 651
  • 834
  • Nothing about the JavaScript `RegExp` interface makes any sense! The Real WTF is the properties on the global `RegExp` constructor object reflecting the last match... ugh. – bobince Apr 19 '10 at 19:25