【问题标题】:Javascript trim double slashesJavascript修剪双斜杠
【发布时间】:2018-12-16 19:23:45
【问题描述】:

我想将//a/url/// 修剪为a/url。 Stackoverflow 上有一些问题,但它们不起作用、解决了另一个问题或太长太复杂。

下面的代码正在运行并且基于Javascript regular expression: remove first and last slash

function trimSlashes(str) {
  str = str.replace(/^\/|\/$/g, '');
  return str.replace(/^\/|\/$/g, '');
};

但是,复制这样的代码并不是很好。像这样的正则表达式如何处理双斜杠?

测试用例

let str1 = trimSlashes('/some/url/here/');
let str2 = trimSlashes('//some/other/url/here///');

预期结果

some/url/here
some/other/url/here

愿望清单

  • 只有一个正则表达式
  • 越短越好

【问题讨论】:

  • 在一行中添加到下面的答案:const trimSlashes = str => str.replace(/^\/+|\/+$/g, '')

标签: javascript regex replace trim


【解决方案1】:

这是另一个没有正则表达式但具有功能性的变体。我不知道性能如何,但我写得很开心,而且看起来不那么神秘。

const newString = '//some/other/url/here///'
.split('/')
.filter(s => s)
.join('/')

编辑:

刚刚运行了一些性能测试,这比正则表达式慢,但如果谨慎使用它可能是微不足道的。

https://jsperf.com/regex-vs-functional/1

【讨论】:

  • 不错的选择! =) 但是,在我添加的链接中有一个这样的答案,它还说“警告词 - 这不像这里的其他 sn-ps 那样快”,所以我的猜测是它可能会更慢。在大多数情况下可能并不明显,但无论如何。
【解决方案2】:

replace(/^\/+|\/+$/g, '') 就是你要找的东西:

两个测试用例的结果:

> '/some/url/here/'.replace(/^\/+|\/+$/g, '');
"some/url/here"

> '//some/other/url/here///'.replace(/^\/+|\/+$/g, '');
"some/other/url/here"

解释:

^\/+  # one or more forward slashes at the beginning
|     # or
\/+$  # one or more forward slashes at the end

【讨论】:

    【解决方案3】:

    使用正则表达式,您必须小心意外匹配。例如,当文本为“//并且这是某行文本中的注释//”时,您是否要修剪斜线?

    如果你不想减少这样的事情,你需要对正则表达式更加小心,这样怎么样?

    let regex = /^\/+([\w\/]+?)\/+$/;
    let matches = regex.exec("//some/other/url/here///");
    let url = matches[1];
    

    https://regex101.com/r/K8CnxP/1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 2012-06-23
      • 1970-01-01
      相关资源
      最近更新 更多