Regex.test () gives true false sequence?

Anyone can explain to me why the local Regex variable and the non-local Regex variable have different output.

var regex1 = /a|b/g; function isAB1() { return regex1.test('a'); } console.log(isAB1()); // true console.log(isAB1()); // false console.log(isAB1()); // true console.log(isAB1()); // false function isAB2() { var regex2 = /a|b/g; return regex2.test('a'); } console.log(isAB2()); // true console.log(isAB2()); // true console.log(isAB2()); // true console.log(isAB2()); // true 

I created a JSFiddle for the same here .

+6
source share
1 answer

You gave your regexp the g flag, which means it will globally match the results. Thus, you explicitly requested your regular expression to keep information about your previous matches.

 var regex1 = /a|b/g; > regex1.lastIndex 0 > regex1.test('a'); true > regex1.lastIndex 1 > regex1.test('a'); false 

If you remove g , you will get the expected results.

You can check the properties of the .lastIndex expression if it is executed.

+6
source

Source: https://habr.com/ru/post/989269/


All Articles