【问题标题】:How to filter specific params from URL?如何从 URL 中过滤特定参数?
【发布时间】:2019-09-14 23:12:13
【问题描述】:

我需要从我的 URL 中过滤掉参数。 比如:

URL = test1/test2/:test3

一些过滤器输出 = test3

URL = test1/:test2/test3

一些过滤器输出 = test2

URL = :test1/test2/test3 

一些过滤器输出 = test1

URL = :test1/test2/test3/:test4 

一些过滤器输出 = test1, test4

我自己尝试了一些 REGEX 和子字符串过滤器,但考虑到上面 1 个过滤器中所有可能的 URL 示例,我无法真正让它工作。

【问题讨论】:

  • 你为什么不向我们展示你的正则表达式?
  • 将您尝试过的代码添加到您的问题中
  • 例如 URL.substring(URL.indexOf(":")+1) 适用于示例 1,输出为 'test 3'。但它不适用于其余部分。 '重复的建议'也不同。

标签: javascript


【解决方案1】:

const REGEX = /\:([A-z0-9-._~:?#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]+)/g;

function findMatches(re, str, matches = []) {
   const m = re.exec(str)
   m && matches.push(m[1]) && findMatches(re, str, matches)
   return matches
}

const urls = [
  'test1/test2/:test3',
  'test1/:test2/test3',
  ':test1/test2/test3',
  ':test1/test2/test3/:test4',
];


const values = urls.map(url => findMatches(REGEX, url));

console.log(values);

【讨论】:

    【解决方案2】:

    像这样?:

    https://regex101.com/r/Jh0BVJ/3/

    regex = new RegExp(/:(?<match>(?:[\w\-.~:?#\[\]@!$&'()*+,;=%]*)\d+)+/gm)
    url = ":test1/test2/test3/:test4"
    console.log(url.match(regex))

    【讨论】:

      【解决方案3】:

      您实际上只是在创建另一个路由器:

      https://github.com/krasimir/navigo

      我没用过 navigo,但它看起来足够强大:

      router
        .on('/user/:id/:action', function (params) {
          // If we have http://example.com/user/42/save as a url then
          // params.id = 42
          // params.action = save
        })
        .resolve();
      
      router.notFound(function (query) {
        // ...
      });
      
      

      现在使用它:

      router.navigate('/products/list');
      
      //Or even with FQDN:
      router.navigate('http://example.com/products/list', true);
      

      【讨论】:

      • 我的问题与如何导航或使用路线无关。我需要过滤掉参数并将它们保存在一个列表中(例如)
      猜你喜欢
      • 2018-03-14
      • 2021-09-25
      • 1970-01-01
      • 2015-11-21
      • 2011-02-01
      • 2015-10-25
      • 2020-11-18
      • 1970-01-01
      • 2017-11-16
      相关资源
      最近更新 更多