JavaScript Regex匹配返回null或undefined

ita*_*o40 1 javascript regex firefox

var url_pattern = new RegExp("(?:http| https)://(www.|.*)someurlhere[.]com/\d\d\d\d/\d\d/\d\d/.*/", "i");
var url=window.location; //or could be document.URL both don't work
url.match(url_pattern);
Run Code Online (Sandbox Code Playgroud)

为什么它返回null,或者未定义但是当我将正则表达式放入支票时它完美无缺,我只想确保URL匹配

jfr*_*d00 6

您的斜线和额外空间有问题,https并且某些句点字符也未正确转义.

使用new RegExp("string")格式时,您必须双重转义任何反斜杠.使用/regexhere/语法要容易得多,因为您不必双重转义许多正则表达式规则中使用的反斜杠.

另外,字符串有一个名为的正则表达式方法.match().正则表达式本身有一个叫做的方法.test().exec().我建议这样:

var url_pattern = /(?:http|https):\/\/(www\.|.*)someurlhere\.com\/\d\d\d\d\/\d\d\/\d\d\/.*\//i;
window.location.href.match(url_pattern);
Run Code Online (Sandbox Code Playgroud)

如果你想继续使用另一种方式来声明它,你会逃避每个反斜杠:

var url_pattern = new RegExp("(?:http|https)://(www\\.|.*)someurlhere[.]com/\\d\\d\\d\\d/\\d\\d/\\d\\d/.*/", "i");
window.location.href.match(url_pattern);
Run Code Online (Sandbox Code Playgroud)