1

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:

  1. Why the two boolean statements are both evaluated to true or false while they are meant to be opposite?
  2. What's difference between Chrome and Node.js in evaluating the two boolean statements?
Lee
  • 2,874
  • 3
  • 27
  • 51

2 Answers2

1

I think it doesn't seem to be an answer, but Node.js hereby outputs:

true true

Here's a terminal console.

PS E:\DevRoom\Kindy> node
> str = '////'
'////'
> re = /^\/+$/g
/^\/+$/g
> console.log(str && re.test(str), str && !re.test(str))
true true
undefined
>

enter image description here

I bet it comes from re-using the global regular expression consequently.

var regex1 = RegExp('foo*');
var regex2 = RegExp('foo*','g');
var str1 = 'table football';

console.log(regex1.test(str1));
// expected output: true

console.log(regex1.test(str1));
// expected output: true

console.log(regex2.test(str1));
// expected output: true

console.log(regex2.test(str1));
// expected output: false
SuperStar518
  • 2,814
  • 2
  • 20
  • 35
0

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • 1
    Thank you! That explains. The reason why I get `false false` in node is because my original code logged the re.test(str) before the two && operator. – Lee Oct 17 '18 at 07:16