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 lastindex read/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:

  1. if lastindex greater length of string, test() , exec() fail, lastindex set 0.
  2. if lastindex equal length of string , if regular expression matches empty string, regular expression matches input starting @ lastindex.
  3. if lastindex equal length of string , if regular expression not match empty string, regular expression mismatches input, , lastindex reset 0.
  4. otherwise, lastindex set 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

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

c# - Exception when attempting to modify Dictionary -