我认为通过实例化一个pattern = new RegExp()并传递一个字符串然后使用.test(value)将与使用/^...$/.test(value)相同,但它们不会看起来是相同的,因为使用RegExp并且每次传递一个字符串失败。这不正确吗?在MDN上似乎可以说这应该有效。
应该全部失败并且他们
var str = "7D>";
var res = /^[A-Za-z0-9\d=!\-@._*]*$/.test(str);
console.log(res); // false which is correct
var patt = /^[A-Za-z0-9\d=!\-@._*]*$/;
var res = patt.test(str);
console.log(res); // false which is correct
var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");
var res = patt.test(str);
console.log(res); // false which is correct, but suspicious based on follow results
应该全部通过而且不要
var str = "7D";
var res = /^[A-Za-z0-9\d=!\-@._*]*$/.test(str);
console.log(res); // true which is correct
var patt = /^[A-Za-z0-9\d=!\-@._*]*$/;
var res = patt.test(str);
console.log(res); // true which is correct
但他们应该通过时,这两种情况都会失败
var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");
var res = patt.test(str);
console.log(res); // false which is NOT correct
var patt = new RegExp("^[A-Za-z0-9\d=!\-@._*]*$");
var res = patt.test(str);
console.log(res); // ALSO false which is NOT correct
答案 0 :(得分:5)
两件事:
使用字符串
/
您执行必须转义反斜杠(一如既往,在字符串文字中)
所以这个:
var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");
应该是
var patt = new RegExp("^[A-Za-z0-9\\d=!\\-@._*]*$");
// ^ ^^ ^^ ^
如果你有标志,你可以将它们作为第二个字符串参数包括在内:
var patt = new RegExp("^[a-z\\d=!\\-@._*]*$", "i");
旁注:
\d
表示“数字”,在规范中定义为0-9
,因此在字符类中包含0-9
和 \d
是冗余