I would like to trim //a/url///
to a/url
. There are a few questions on Stackoverflow but they don't work, solves another problem or is too long and complex.
The code below is working and is based on Javascript regular expression: remove first and last slash
function trimSlashes(str) {
str = str.replace(/^\/|\/$/g, '');
return str.replace(/^\/|\/$/g, '');
};
However it's not very nice to duplicate code like that. How would a regex look like that takes care of double slashes as well?
let str1 = trimSlashes('/some/url/here/');
let str2 = trimSlashes('//some/other/url/here///');
some/url/here
some/other/url/here
Here's another variation without a regex but with a functional flair. I don't know about the performance but I had fun writing it and seems less cryptic.
const newString = '//some/other/url/here///'
.split('/')
.filter(s => s)
.join('/')
Edit:
Just ran some perf tests and this is slower than a regex but it might be insignificant if used sparingly.
replace(/^\\/+|\\/+$/g, '')
is what you're looking for:
Result with both test cases:
> '/some/url/here/'.replace(/^\/+|\/+$/g, '');
"some/url/here"
> '//some/other/url/here///'.replace(/^\/+|\/+$/g, '');
"some/other/url/here"
Explained:
^\/+ # one or more forward slashes at the beginning
| # or
\/+$ # one or more forward slashes at the end
With regexes you must be careful of unintended matches. for example do you want to trim the slash when the text is "// and this is a comment in some line of text//"?
If you don't want to trim things like that down you need to be a little more careful with the regex, how about this?
let regex = /^\/+([\w\/]+?)\/+$/;
let matches = regex.exec("//some/other/url/here///");
let url = matches[1];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.