new RegExp("regex");
使用和/same_regex/
测试目标字符串之间有什么区别吗?我问这个问题是因为我在使用这两种方法时得到了不同的验证结果。这是我用来验证电子邮件字段的片段:
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");
}
我得到了两个不一致的结果:
电子邮件匹配的正则表达式1 电子邮件不匹配的正则表达式2
我想知道这里是否有任何区别,或者我在这个特定示例中省略了某些内容?
有关可执行示例,请参阅此处