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."
source share