In case using RegExp is not an option , or you need to handle corner cases when working with URLs (for example, double / triple slashes or blank lines without complex replacements) or using additional processing, here is a less obvious, but more functional 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 filter() snippet, a function can implement more complex logic than just filtering empty strings (which is the default behavior).
A word of warning is not as fast as the other fragments here.
Kid Binary Dec 04 '17 at 16:21 2017-12-04 16:21
source share