javascript - Why does RegEx.test changes the result in subsequent calls? -
this question has answer here:
why following go true false;
var r = /e/gi; r.test('e'); // true r.test('e'); // false and continue switching true, false, true, false ......
its because of g flag. starts remembering last index of match , when r.test next time, starts index. why alternates between true , 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
lastindexread/write integer property of regular expressions specifies index @ start next match. ...this property set if regular expression used "g" flag indicate global search. following rules apply:
- if
lastindexgreater length of string,test(),exec()fail,lastindexset 0.- if
lastindexequal length of string , if regular expression matches empty string, regular expression matches input starting @lastindex.- if
lastindexequal length of string , if regular expression not match empty string, regular expression mismatches input, ,lastindexreset 0.- otherwise,
lastindexset next position following recent match.
the bold text above answers behaviour observed. after first match, e, lastindex set 1, indicate index next match should tried. according 3rd point seen above, since lastindex equal length of string , regular expression doesn't match empty string, returns false , resets lastindex 0.
Comments
Post a Comment