Maielo Maielo - 1 year ago 86
Javascript Question

Why when looping regexObj.test(str) is logging each iteration different result?

Running code below is logging each iteration different result

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

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


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

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download