Javascript trim 双斜杠

Javascript trim double slashes

我想trim//a/url///a/url。 Whosebug 上有几个问题,但它们不起作用,解决了另一个问题或太长太复杂。

下面的代码是基于 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

心愿单

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

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

如果您不想 trim 这样的事情,您需要更加小心地使用正则表达式,这个怎么样?

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

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

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

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

编辑:

只是 运行 一些性能测试,这比正则表达式慢,但如果谨慎使用它可能无关紧要。

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