如何针对URL字符串测试URL匹配模式

时间:2018-09-07 16:31:33

标签: javascript google-chrome-extension firefox-addon firefox-webextensions

我可以使用匹配模式获取浏览器标签

private static void setOptionalParameter(Runnable action) {

    try {
        action.run();
    } catch (IllegalArgumentException ignored) {
    }
}

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns

在标签更新事件中,我可以获取标签ID和网址,但是如何测试该标签与我的原始匹配模式匹配?

setOptionalParameter(() -> {
    ProductType productType = ...some operation with source...;
    Material material = ...some operation with source...;

    product.doSomethingWith2Args(productType, material);
});

1 个答案:

答案 0 :(得分:1)

一个简单的自写星号匹配器将是:

function match(pattern, url) {
  pattern = pattern.split("/");
  url = url.split("/");
  
  while(url.length) {
   const p = pattern.shift();
   if(p !== url.shift() && p !== "*")
    return false;
  }
  return true;
}

console.log(
  match("https://example.com/*/test/", "https://example.com/a/test/"),
  match("https://example.com/*/test/", "https://example.com/a/b/")
);