1

If I use RegExp test(), it gives the correct answer the first time, but thereafter it returns the inverse result (if the match is found) or just false if it's not:

let regex = new RegExp('bird|dog', 'g')

console.log(regex.test('Imma bird')) // output: true
console.log(regex.test('Imma dog')) // output false !
console.log(regex.test('Imma dog')) // output true
console.log(regex.test('Imma bird')) // output false !?
console.log(regex.test('Imma bird')) // output true
console.log(regex.test('Imma bird')) // output false ??
console.log(regex.test('Imma believer')) // output false
console.log(regex.test('Imma believer')) // output false
console.log(regex.test('Imma believer')) // output false

If I don't use the 'g' qualifier, all works as expected:

let regex = new RegExp('bird|dog')

console.log(regex.test('Imma bird')) // output true
console.log(regex.test('Imma bird')) // output true
console.log(regex.test('Imma believer')) // output false
console.log(regex.test('Imma believer')) // output false

Clearly there is something I don't understand at play here. But what?

David Mold
  • 198
  • 3
  • 5
  • 2
    That's what the "g" flag does. The regex "remembers" where the last match ended and starts from there on the next search. – Pointy Nov 19 '19 at 18:08

1 Answers1

1

The g flag tells the RegExp object to remember the position of the last match and resume from there the next time a match (or test, in this case) is attempted.

Soviut
  • 88,194
  • 49
  • 192
  • 260