Is there any difference between using new RegExp("regex");
and /same_regex/
to test against a target string? I am asking this question because I got different validating result while use these two approaches. Here is the snippet I used to validate an email field:
var email="[email protected]@foo.com";
var regex1 = new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
var regex2 = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
//using RegExp object
if(regex1.test(email)) {
console.log("email matched regex1");
} else {
console.log("email mismatched regex1");
}
//using slash notation
if(regex2.test(email)) {
console.log("email matched regex2");
} else {
console.log("email mismatched regex2");
}
I got two inconsistent results:
email matched regex1 email mismatched regex2
I am wondering if there is any difference here or I omitted something in this specific example?
For an executable example please refer to here
The expression new RegExp(/ab+c/, flags) will create a new RegExp using the source of the first parameter and the flags provided by the second. When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.
RegExp ObjectA regular expression is a pattern of characters. The pattern is used to do pattern-matching "search-and-replace" functions on text. In JavaScript, a RegExp Object is a pattern with Properties and Methods.
If you use the constructor to create a new RegExp object instead of the literal syntax, you need to escape the \
properly:
new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$")
This is necessary as in JavaScript any unknown escape sequence \x
is interpreted as x
. So in this case the \.
is interpreted as .
.
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