I have these strings in javascript:
/banking/bonifici/italia
/banking/bonifici/italia/
and I would like to remove the first and last slash
In case if using RegExp is not an option, or you have to handle corner cases while working with URLs (such as double/triple slashes or empty lines without complex replacements), or utilizing additional processing, here's a less obvious, but more functional-style solution:
const urls = [
'//some/link///to/the/resource/',
'/root',
'/something/else',
];
const trimmedUrls = urls.map(url => url.split('/').filter(x => x).join('/'));
console.log(trimmedUrls);
In this snippet filter()
function can implement more complex logic than just filtering empty strings (which is default behavior).
Word of warning - this is not as fast as other snippets here.