我在javascript中有这些字符串:
/banking/bonifici/italia
/banking/bonifici/italia/
Run Code Online (Sandbox Code Playgroud)
如果它存在,我想删除第一个和最后一个斜杠.
我试过^\/(.+)\/?$但它不起作用.
在stackoverflow中阅读一些帖子我发现php有修剪功能,我可以使用他的javascript翻译(http://phpjs.org/functions/trim:566)但我更喜欢"简单"的正则表达式.
ken*_*ytm 170
return theString.replace(/^\/|\/$/g, '');
Run Code Online (Sandbox Code Playgroud)
"用空字符串替换all(/.../g)前导斜杠(^\/)或(|)尾部斜杠(\/$)."
Dan*_*uis 32
这里没有真正的理由使用正则表达式,字符串函数可以正常工作:
var string = "/banking/bonifici/italia/";
if (string.charAt(0) == "/") string = string.substr(1);
if (string.charAt(string.length - 1) == "/") string = string.substr(0, string.length - 1);
// string => "banking/bonifici/italia"
Run Code Online (Sandbox Code Playgroud)
在jsFiddle上看到这个.
参考文献:
一个衬垫,无正则表达式,处理多次发生
const trimSlashes = str => str.split('/').filter(v => v !== '').join('/');
console.log(trimSlashes('/some/path/foo/bar///')); // "some/path/foo/bar"
Run Code Online (Sandbox Code Playgroud)
如果不是使用RegExp ,或者在使用URL(例如,双/三斜杠或没有复杂替换的空行)或使用其他处理时不得不处理一些极端情况,这虽然不那么明显,但功能更多-样式解决方案:
const urls = [
'//some/link///to/the/resource/',
'/root',
'/something/else',
];
const trimmedUrls = urls.map(url => url.split('/').filter(x => x).join('/'));
console.log(trimmedUrls);Run Code Online (Sandbox Code Playgroud)
在此代码段中,filter()函数可以实现比仅过滤空字符串(这是默认行为)更复杂的逻辑。
警告词-这不像这里的其他摘要那么快。