我正在编写一个 Chrome 扩展,它允许用户修改特定网站上的内容。我希望用户能够使用通配符指定这些网站,例如 http://*.google.com
或 http://google.com/*
我找到了以下代码
currentUrl = "http://google.com/";
matchUrl = "http://*.google.com/*";
match = RegExp(matchUrl.replace(/\*/g, "[^]*")).test(currentUrl);
但是它有一些问题。
http://test.google.com/
匹配
http://google.com/
不匹配
http://test.google.com
不匹配
http://.google.com/
匹配
Clarification:
http://google.com
Isn't a match, and that is the real problem.
那么我怎样才能创建一个 JavaScript 代码片段来检查是否存在正确的匹配?
最佳答案
我建议将 URL 解析为协议(protocol)、基本部分和其余部分,然后重新构建验证正则表达式,将基本部分中的 *
替换为 (?:[^/]*\\.)*
,否则使用 (?:/[^]*)?
。此外,您必须使用 .replace(/[?()[\]\\.+^$|]/g, "\\$&")
转义所有其他特殊字符。您还需要 anchor (^
表示字符串的开头,$
表示字符串的结尾位置)来匹配整个字符串。不区分大小写的 /i
修饰符只是使模式不区分大小写的一个好处。
因此,对于这个确切的 matchUrl
,正则表达式将如下所示
/^http:\/\/(?:[^\/]*\.)*google\.com(?:\/[^]*)?$/
请参阅regex demo
var rxUrlSplit = /((?:http|ftp)s?):\/\/([^\/]+)(\/.*)?/;
var strs = ['http://test.google.com/', 'http://google.com/','http://test.google.com', 'http://.google.com/','http://one.more.test.google.com'];
var matchUrl = "http://*.google.com/*";
var prepUrl = "";
if ((m=matchUrl.match(rxUrlSplit)) !== null) {
prepUrl = m[1]+"://"+m[2].replace(/[?()[\]\\.+^$|]/g, "\\$&").replace(/\*\\./g,'(?:[^/]*\\.)*').replace(/\*$/,'[^/]*');
if (m[3]) {
prepUrl+= m[3].replace(/[?()[\]\\.+^$|]/g, "\\$&").replace(/\/\*(?=$|\/)/g, '(?:/[^]*)?');
}
}
if (prepUrl) {
// console.log(prepUrl); // ^http://(?:[^/]*\.)*google\.com(?:/[^]*)?$
var rx = RegExp("^" + prepUrl + "$", "i");
for (var s of strs) {
if (s.match(rx)) {
console.log(s + " matches!<br/>");
} else {
console.log(s + " does not match!<br/>");
}
}
}
关于Javascript 与通配符匹配 URL - Chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39094017/