我认为通过实例化一个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
Run Code Online (Sandbox Code Playgroud)
应该全部通过而他们不要
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
Run Code Online (Sandbox Code Playgroud)
但是当他们应该通过时,这两个尝试都会失败
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
Run Code Online (Sandbox Code Playgroud)
两件事情:
您不包括/使用字符串的时间
你也有逃避反斜杠(一如既往,在一个字符串)
所以这:
var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");
Run Code Online (Sandbox Code Playgroud)
应该
var patt = new RegExp("^[A-Za-z0-9\\d=!\\-@._*]*$");
// ^ ^^ ^^ ^
Run Code Online (Sandbox Code Playgroud)
如果你有标志,你将它们包含为第二个字符串参数:
var patt = new RegExp("^[a-z\\d=!\\-@._*]*$", "i");
Run Code Online (Sandbox Code Playgroud)
边注:
\d表示在规范中定义的"数字" 0-9,因此在字符类中具有0-9 和 \d在字符类中是冗余的
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |