Why is (new RegExp("\\w") === /\w/) false in JS?

javascript, regex

Solution

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`.

Problem

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.

Original source