Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using "new RegExp" and using forward slash notation to create a regular expression?

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

like image 767
didxga Avatar asked May 27 '11 08:05

didxga


People also ask

What does New RegExp do in JavaScript?

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.

What is forward slash in regex JavaScript?

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.

What does RegExp mean in JavaScript?

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.


1 Answers

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 ..

like image 103
Gumbo Avatar answered Oct 30 '22 05:10

Gumbo