我需要将 URL 与字符串模式进行匹配,但我想避免使用 RegExp 以保持模式简单易读。
我希望能够拥有像 http://*.example.org/*
这样的模式,它应该等同于 /^http:\/\/。 *\.example.org\/.*$/
在正则表达式中。该 RegExp 还应该说明为什么我想让它更具可读性。
基本上,我想要适用于 URL 的类似 glob 的模式。问题是:普通的 glob 实现将 /
视为分隔符。这意味着,http://foo.example.org/bar/bla
不符合我的简单模式。
因此,可以忽略斜杠的 glob 实现会很棒。有这样的东西或类似的东西吗?
最佳答案
对于类似 glob 的行为,您可以从这样的函数开始:
function glob(pattern, input) {
var re = new RegExp(pattern.replace(/([.?+^$[\]\\(){}|\/-])/g, "\\$1").replace(/\*/g, '.*'));
return re.test(input);
}
然后称它为:
glob('http://*.example.org/*', 'http://foo.example.org/bar/bla');
true
关于javascript - 在 JavaScript 中是否有类似 glob 但用于 URL 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24558442/