31

Why do

console.log(/a/ == /a/);

and

var regexp1 = /a/;
var regexp2 = /a/;
console.log(regexp1 == regexp2);

both return false?

sp00m
  • 47,968
  • 31
  • 142
  • 252

4 Answers4

56

Try this:

String(regexp1) === String(regexp2))

You are getting false because those two are different objects.

ioseb
  • 16,625
  • 3
  • 33
  • 29
  • error.errorVal.requiredPattern.toString() == ("^(0|[1-9]\d*)(.\d+)?$").toString() false // not working error.errorVal.requiredPattern "^(0|[1-9]\d*)(.\d+)?$" – Bravo Jul 17 '20 at 14:46
  • I have tried to convert to string but it is not working .. – Bravo Jul 17 '20 at 14:46
  • If using `new` to create the String, you need to call valueOf since an Object is being created (rather than a primitive String literal) - e.g. (new String(regexp1)).valueOf() === (new String(regexp2)).valueOf() – Shaun Oct 01 '20 at 18:40
14

"Problem":

regex is an object- a reference type, so the comparsion is done by reference, and those are two different objects.

console.log(typeof /a/); // "object"

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

MDN

Solution:

​var a = /a/;
var b = /a/;
console.log(​​​a.toString() === b.toString()); // true! yessss!

Live DEMO

Another "hack" to force the toString() on the regexes is:

console.log(a + "" === b + "");​
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • error.errorVal.requiredPattern.toString() == ("^(0|[1-9]\d*)(.\d+)?$").toString() false // not working error.errorVal.requiredPattern "^(0|[1-9]\d*)(.\d+)?$" – Bravo Jul 17 '20 at 14:54
  • it is not working when i use reactive form error and try to match with same pattern which i inserted in the validators – Bravo Jul 17 '20 at 15:27
4

Just a guess - but doesn't JavaScript create a RegExp object for your regex, and therefore because you have created two different objects (even though they have the same "value") they're actually different?

gdoron
  • 147,333
  • 58
  • 291
  • 367
Andy Shellam
  • 15,403
  • 1
  • 27
  • 41
2

For primitive data types like int, string, boolean javascript knows what to compare, but for objects like date or regex that operator only looks at the place in memory, because you define your regexes independently they have two different places in memory so they are not equal.

omerkirk
  • 2,527
  • 1
  • 17
  • 9