0

I was able to work around this issue as it turned out I didn't need /g. But I was wondering if anyone would be able to explain why the following behavior occurred.

x = RegExp( "w", "gi" )
x.test( "Women" )
    = true
x.test( "Women" )
    = false

It would continue to alternate between true and false when evaluating the expression. Which was an issue because I was using the same compiled RegExp on a list of strings, leading some to evaluate to false when they should have been true.

Chris
  • 631
  • 1
  • 9
  • 17

3 Answers3

2

You should not be using global modifier in a regex used for test, because it preserves the index of the last search and starts the next test from there.

I'd asked the same question.

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test

As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

Essentially, the RegExp object x keeps track of its last match internally. When you call .test again, it attempts to match starting after the "w"

Of course this is only true of a regex object instance.

> /w/gi.test('Women')
true
> /w/gi.test('Women')
true
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

When you use the g flag, the regex stores the end position of the match in its lastIndex property. The next time you call any of test(), exec(), or match(), the regex will start from that index in the string to try and find a match.

When no match is found, it will return null, and lastIndex is reset to 0. This is why your test kept alternating. It would match the W, and then lastIndex would be set to 1. The next time you called it, null would be returned, and lastIndex would be reset.

A pitfall related to this is when your regex can match the empty string. In that case, lastIndex will not change, and if you are getting all matches, there will be an infinite loop. In this case you should manually adjust lastIndex if it matched the empty string.

Sergiu Toarca
  • 2,697
  • 20
  • 24