如何匹配用户在 Firefox 扩展中输入的模式列表
How to match list of patterns entered by the user in firefox extension
Mozilla 插件有一个 MatchPattern API 将 URL 与模式进行比较。我寻找的不是固定的 URL 模式,而是用户给出的列表。 mozilla 提供的 link 中的示例采用硬编码模式。如何让变量 match
读取存储中的 URL 列表?
var match = new MatchPattern("*://mozilla.org/");
var uri = BrowserUtils.makeURI("https://mozilla.org/");
match.matches(uri); // < true
uri = BrowserUtils.makeURI("https://mozilla.org/path");
match.matches(uri); // < false
原来如此琐碎。简单地说,通过将引用 URL 存储在一个数组中,然后构建一个模式,一个接一个地遍历数组项,直到找到手头的 url 与任何数组项的匹配项。
我最终使用了 search
函数而不是 match
。这件作品看起来像这样:
//the url to be tested.
var url="www.example.com";
for (var x=0; x<myArray.length; x++) //loop over the list
{
//for a constructing a RegEx in a string.
//the following says the pattern startes with myArray[x], followed by "/[anything]/"
//We use "\" in the string to represent "\" in the Regex.
//We write "\/" in the string to represent the Regex "\/"
var pattern= "("+myArray[x]+")"+"(\/.*)*(\/)*";"
//test if the pattern equals the value
if(url.search(pattern)==0)
console.log("url matched");
else
console.log("url did not match");
}//end for
Mozilla 插件有一个 MatchPattern API 将 URL 与模式进行比较。我寻找的不是固定的 URL 模式,而是用户给出的列表。 mozilla 提供的 link 中的示例采用硬编码模式。如何让变量 match
读取存储中的 URL 列表?
var match = new MatchPattern("*://mozilla.org/");
var uri = BrowserUtils.makeURI("https://mozilla.org/");
match.matches(uri); // < true
uri = BrowserUtils.makeURI("https://mozilla.org/path");
match.matches(uri); // < false
原来如此琐碎。简单地说,通过将引用 URL 存储在一个数组中,然后构建一个模式,一个接一个地遍历数组项,直到找到手头的 url 与任何数组项的匹配项。
我最终使用了 search
函数而不是 match
。这件作品看起来像这样:
//the url to be tested.
var url="www.example.com";
for (var x=0; x<myArray.length; x++) //loop over the list
{
//for a constructing a RegEx in a string.
//the following says the pattern startes with myArray[x], followed by "/[anything]/"
//We use "\" in the string to represent "\" in the Regex.
//We write "\/" in the string to represent the Regex "\/"
var pattern= "("+myArray[x]+")"+"(\/.*)*(\/)*";"
//test if the pattern equals the value
if(url.search(pattern)==0)
console.log("url matched");
else
console.log("url did not match");
}//end for