Why do
console.log(/a/ == /a/);
and
var regexp1 = /a/; var regexp2 = /a/; console.log(regexp1 == regexp2);
both return false
?
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?
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.
To search with a regular expression:Choose Edit > Find and Replace, or press Ctrl-F (Cmd-F).
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.
Try this:
String(regexp1) === String(regexp2))
You are getting false because those two are different objects.
"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 regex
es is:
console.log(a + "" === b + "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With