This can be accomplished by a combination of Node's path and URL:
- Require the packages:
const nodeUrl = require('url')
const nodePath = require('path')
- Start by making a URL object to work with:
> const myUrl = new nodeUrl.URL('https://example.com')
- Use
pathname=
and path.join
to construct any possible combination:
> myUrl.pathname = nodePath.join('/search', 'for', '/something/')
'/search/for/something/'
(you can see how liberal path.join
is with arguments)
- At this point your URL reflects the ultimate desired result:
> myUrl.toString()
'https://example.com/search/for/something/'
Why this approach?
This technique uses built-in libraries. The less third-party dependencies the better, when it comes to CVEs, maintenance, etc.
Nothing will be more proven or better tested than standard libs.
PS: Never manipulate URLs as strings!
When I review code I'm adamant about never manipulating URLs as strings manually. For one, look how complicated the spec is.
Secondly, the absence/presence of a trailing/prefixed slash (/
) should not cause everything to break! You should never do:
const url = `${baseUrl}/${somePath}`
and especially not:
uri: host + '/' + SAT_SERVICE + '/' + CONSTELLATION + '/',
Of which I have seen.
path.posix.join('/one/two/three', 'four') // '/one/two/three/four
,path.posix.join('/one/two/three/', 'four') // '/one/two/three/four
,path.posix.join('/one/two/three/', '/four') // '/one/two/three/four
path.posix.join('http://localhost:9887/one/two/three/', '/four')
, the join gets rid of one of the double slashes inhttp://
'http://localhost:9887/one/two/three/'.replace(/^\/+|\/+$/, '') + '/' + '/four'.replace(/^\/+|\/+$/, '')
and you could doString.prototype.trimSlashes = function() { return this.replace(/^\/+|\/+$/, ''); }
if you don't want to type the regular expression over and over again. stackoverflow.com/a/22387870/2537258['http://localhost:9887/one/two/three/', '/four'].map((part) => part. replace(/^\/+|\/+$/, '')).join('/')