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="didxga@gmail.comblah@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

16
задан CertainPerformance 28 July 2018 в 04:44
поделиться