1

I just noticed the following strange behavior (both in browsers and :

> a = /^\/foo/g
/^\/foo/g
> a.test("/foo")
true
> a.test("/foo")
false
> a.test("/foo")
true
> a.test("/foo")
false
> a.test("/foo")
true

What kind of mad science we have here? How can I prevent this behavior?

I just want to have a regex variable that checks if a string matches the pattern globally.


Documentation pages don't seem to bring some light there... I'd really appreciate a link to documentation references.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

1 Answers1

3

Set the lastIndex of your regex to 0 after each test.

a = /^\/foo/g
a.test("/foo"); //true
a.test("/foo"); //false
a.test("/foo"); //true
a.lastIndex = 0; //reset the index to start the next match at beginning
a.test("/foo"); //true
berrberr
  • 1,914
  • 11
  • 16