How to compare two regexps?

自闭症网瘾萝莉.ら 提交于 2020-06-08 15:45:12

问题


Since you can store a regexp in a variable

var regexp = /a/;

why do

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

and even

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

both return false?


回答1:


Try this:

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

You are getting false because those two are different objects.




回答2:


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



回答3:


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?




回答4:


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.



来源:https://stackoverflow.com/questions/11032784/how-to-compare-two-regexps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!