p.test(s); true > p.test(s); false; When I run this code on the Chrome cons...">

Javascript Regex with .test ()

> var p = /abc/gi; > var s = "abc"; > p.test(s); true > p.test(s); false; 

When I run this code on the Chrome console, I have this output above. Each time I call '.test ()', I get a different value. Can someone explain to me why this is happening? thanks

+6
source share
3 answers

The behavior is due to the modifier "g", i.e. corresponds to three times, does not correspond to the fourth time:

 > var p = /a/gi; > var s = "aaa"; > p.test(s) true > p.test(s) true > p.test(s) true > p.test(s) false 

See a similar question: Why does RegExp with a global flag in Javascript give incorrect results?

+8
source

The g flag causes the RegExp literal to be used to track LastIndex matches

If you need:

 print( p.test(s), p.lastIndex ) print( p.test(s), p.lastIndex ) 

You will see

 true,3 false,0 

So, the 2nd test failed, as there is no incremental match with the 1st.

+5
source

This is because of the / g flag. Each consecutive search starts with the last character matching the previous search. In your case, in the second run, it starts at the end of the line and returns false. The third time it starts from the beginning. Etc.

Also, take a look at this question: Why does RegExp with a global flag in Javascript give incorrect results?

+2
source

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


All Articles