Javascript: Insane boolean test using !! operator

When you enter the following function call into the chrome console:

(function(regex, str){ console.log(regex.test(str)) console.log(!regex.test(str)) console.log(! regex.test(str)) console.log( !regex.test(str)) console.log( ! regex.test(str)) })(new RegExp("new", "gmi"), "new") 

I get the following results:

 true true false true false 

Can someone explain why the 3rd and 5th tests return false ? And why the first and second are both true.

+5
source share
2 answers

You turn on the g modifier, so the regex object maintains a match execution state. In other words, each call does not match.

Your first call matches the string "new" , and the regular expression updates the position to the end of the line. The next match will fail (so you see true for !regexp.test(str) ). It fails because the string "new" does not appear at the end of the string "new".

Now we have finished the end of the line, so the next test starts as the first. It matches again, so yours ! turns true to false . One that after this does not match, and one after that will start again and will correspond.

Please note that spaces are around ! in tests have nothing to do with behavior.

edit - try this option:

 (function(regex, str){ console.log(regex.test(str) + " - " + regex.lastIndex) console.log(!regex.test(str) + " - " + regex.lastIndex) console.log(! regex.test(str) + " - " + regex.lastIndex) console.log( !regex.test(str) + " - " + regex.lastIndex) console.log( ! regex.test(str) + " - " + regex.lastIndex) })(new RegExp("new", "gmi"), "new") 

You will see that the .lastIndex property toggles between 0 and 3 .

I think the moral of this story is "don't use 'g' unless you really know what you want."

+10
source

I will explain to you what is happening. Go through the comments. Its in the form

 regex.lastIndex, actual value, negated value // code below (function(regex, str){ console.log(regex.test(str)) // 0, true, false console.log(!regex.test(str)) // 3, false, true => lastIndex set to 0 console.log(! regex.test(str)) // 0, true, false console.log( !regex.test(str)) // 3, false, true => lastIndex set to 0 console.log( ! regex.test(str)) // 0, true, false })(new RegExp("new", "gmi"), "new") 

MDN

If lastIndex is equal to the length of the string, and if the regular expression does not match the empty string, then the regular expression does not match the input, and lastIndex is reset - 0.

So lastIndex updated if the global regular expression is used more than once, and it decides where to start matching.

+3
source

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


All Articles