sel*_*oup 5 javascript regex url glob
我需要将URL与字符串模式进行匹配,但我想避免RegExp来使模式保持简单和可读性。
我希望能够有类似的模式http://*.example.org/*
,这应该与/^http:\/\/.*\.example.org\/.*$/
RegExp中的模式相同。该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);
}
Run Code Online (Sandbox Code Playgroud)
然后将其称为:
glob('http://*.example.org/*', 'http://foo.example.org/bar/bla');
true
Run Code Online (Sandbox Code Playgroud)