Alex Rivera | Logout

How to compare two regexps?

Asked 2012-06-14T12:10:29.133
31

Why do

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

and

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

both return false?

Edit
Report

1 Answer

15

"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 + "");​
answered 2012-06-14T12:13:00.987

Your Answer