I have a few lines of javascript code as below:
var str = '////';
var re = /^\/+$/g
console.log(str && re.test(str), str && !re.test(str));
The output of the code in Node.js
are false, false
and in Chrome
Client side are true, true
I'm quite confused and would anyone help to understand:
true
or false
while they are meant to be opposite? Chrome
and Node.js
in evaluating the two boolean statements? From MDN (emphasis mine):
As with
exec()
(or in combination with it),test()
called multiple times on the same global regular expression instance will advance past the previous match.
So, since your regular expression is global, the following happens:
var str = '////';
var re = /^\/+$/g;
console.log(re.test(str)); // "true" — matches and regex advances
console.log(re.test(str)); // "false" — remainder no longer matches
In comparison, for a non-global expression:
var str = '////';
var re = /^\/+$/;
console.log(re.test(str)); // matches, "true"
console.log(re.test(str)); // matches, "true"
Note: for the code in your question, I get the same output in Node as I do in Chrome and in Firefox: true true
.