9

Why does the following go from true to false;

var r = /e/gi;
r.test('e'); // true
r.test('e'); // false

and then it continue switching true, false, true, false ......

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Edwin Reynoso
  • 1,511
  • 9
  • 18

1 Answers1

12

Its because of the g flag. It starts remembering the last index of the match and when you do r.test next time, it starts from that index. That is why it alternates between true and false. Try this

var r = /e/gi;
console.log(r.test('e'));
# true
console.log(r.lastIndex);
# 1
console.log(r.test('e'));
# false
console.log(r.lastIndex);
# 0
console.log(r.test('e'));
# true
console.log(r.lastIndex);
# 1
console.log(r.test('e'));
# false

Quoting MDN Documentation on RegExp.lastIndex,

The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match. ...

This property is set only if the regular expression used the "g" flag to indicate a global search. The following rules apply:

  1. If lastIndex is greater than the length of the string, test() and exec() fail, then lastIndex is set to 0.
  2. If lastIndex is equal to the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting at lastIndex.
  3. If lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.
  4. Otherwise, lastIndex is set to the next position following the most recent match.

The bold text above answers the behaviour you observed. After the first match, e, the lastIndex is set to 1, to indicate the index from which the next match should be tried. According to the 3rd point seen above, since the lastIndex is equal to the length of the string and the regular expression doesn't match the empty string, it returns false and resets lastIndex to 0.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497