-1

Running code below is logging each iteration different result

var re = /[a-z]+/g;
var str= 'test';

for(var i = 0; i < 5; i++) {

    console.log(re.test(str));

}
// result : first iteration logs `true`, second `false`, third `true` ...

Can someone please explain, why is this happening ? And why is it working when /g global modifier is removed ?

Maielo
  • 692
  • 1
  • 6
  • 20

1 Answers1

0

if you check the MDN documentation of test, you will find out that it's not a pure function, but it has a side effect that changes your re variable:

test() called multiple times on the same global regular expression instance will advance past the previous match

when using the /.../g modifier, after exhausting all matches (i.e. the first iteration), the regex position will be at the end of string where it will not match, but there seems to be an undefined behaviour which resets the regex position to the beginning of string (according to what you observed at the 3rd iteration)

without the global modifier, the regex can be executed multiple times from the start position

Aprillion
  • 21,510
  • 5
  • 55
  • 89