How to compare two regexps?

前端 未结 4 1326
离开以前
离开以前 2021-01-17 10:06

Why do

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

and

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

bo

4条回答
  •  旧巷少年郎
    2021-01-17 10:39

    "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 + "");​
    

提交回复
热议问题