Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two regexps?

Why do

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

and

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

both return false?

like image 913
sp00m Avatar asked Jun 14 '12 12:06

sp00m


People also ask

How can you tell if two expressions are equivalent?

We say that two regular expressions R and S are equivalent if they describe the same language. In other words, if L(R) = L(S) for two regular expressions R and S then R = S. Examples. Are R and S equivalent?

What is\\ in regular expression?

You also need to use regex \\ to match "\" (back-slash). Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

Can I use regex in Ctrl F?

To search with a regular expression:Choose Edit > Find and Replace, or press Ctrl-F (Cmd-F).

How do you test a regular expression?

To test a regular expression, first search for errors such as non-escaped characters or unbalanced parentheses. Then test it against various input strings to ensure it accepts correct strings and regex wrong ones. A regex tester tool is a great tool that does all of this.


2 Answers

Try this:

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

You are getting false because those two are different objects.

like image 183
ioseb Avatar answered Oct 03 '22 01:10

ioseb


"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 + "");​ 
like image 20
gdoron is supporting Monica Avatar answered Oct 03 '22 00:10

gdoron is supporting Monica