I tried the following in Chrome’s console:
var r1 = new RegExp("\\w"); // → /\w/
var r2 = /\w/; // → /\w/
r1 === r2; // → false
r1 == r2; // → false
r1.toString() === r2.toString(); // → true
r1.source === r2.source; // → true
I don't understand why it does that.
They are two different RegExp
instances, so by directly comparing them with ==
or ===
you're comparing two unequal references, resulting in false
.
But when you compare either their toString()
serializations or their sources, you're comparing their string representations by value. Since they're basically the exact same pattern and flags, comparing their string representations will return true
.
Here is a quote from the Comparison Operators documentation on MDN:
Note that an object is converted into a primitive if, and only if, its comparand is a primitive. If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object.
new RegExp("\\w")
is an object and so is /\w/
. Both instantiated separately. Need I say more?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With