【发布时间】: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