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
......
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
......
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:
- If
lastIndex
is greater than the length of the string,test()
andexec()
fail, thenlastIndex
is set to 0.- 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 atlastIndex
.- 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, andlastIndex
is reset to 0.- 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.