【问题标题】:Clean url from queryparams and urlParams with javascript regex or react-router使用 javascript regex 或 react-router 从 queryparams 和 urlParams 中清除 url
【发布时间】:2021-09-14 13:15:26
【问题描述】:

我必须从数字和查询参数中清除 url。 E.G

/hi/1/2 --> 必须是 --> /hi

/hi?1111 --> 必须是 --> /hi

/hi/hello/how/are/you/1/1/1 --> 必须是 /hi/hello/how/are/you

我已经用 window.location.pathname 完成了,但是斜线后面的数字仍然在这里。

我在想也许是用正则表达式或类似的东西?

有什么想法吗?

我也尝试了一些 react-router 的钩子,但没有成功

【问题讨论】:

  • 如果您正在创建这些路由,请修复这些重定向发生的来源。

标签: javascript reactjs regex


【解决方案1】:
function formatURL(arr = []) {
  // Stop code if array is empty.
  if (!arr.length) { console.error('No array provided.', arr); return arr; }

  // Format each element inside the array, replace old array value with the new value, output the result.
  arr.forEach(e => { arr.shift(); arr.push(e.match(/[A-z/]+/)[0]); console.log('Formatted URL:', arr[arr.length - 1]); })
  
  // Return array with formatted URLs.
  return arr;
}

// Call function, provide an array of unformatted URLs to it as the argument.
formatURL(['/hi/hello/how/are/you/1/1/1', '/hi/1/2', '/hi?1111']);

您好,也许这可以解决您的问题?另外,不要讨厌,但您应该在发表这样的评论之前阅读正则表达式,因为互联网上已经有大量可用资源。话虽如此,希望它对你有用!

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2016-11-09
    • 2022-09-22
    • 2018-09-16
    • 2012-06-22
    • 2017-02-04
    • 1970-01-01
    • 2013-01-17
    • 2020-09-13
    相关资源
    最近更新 更多