我想将 //a/url///
trim 为 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
愿望 list
- 只是一个正则表达式
- 越短或越快越好
最佳答案
这是另一种没有正则表达式但具有功能性的变体。我不知道性能如何,但我写得很开心,而且看起来不那么神秘。
const newString = '//some/other/url/here///'
.split('/')
.filter(s => s)
.join('/')
编辑:
刚刚运行了一些性能测试,这比正则表达式慢,但如果谨慎使用,它可能微不足道。
关于Javascript trim 双斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53805676/