Is this safe to use require(\"path\").join
to concatenate URLs, for example:
require(\"path\").join(\"http://example.com\", \"ok\");
//returns
If you use Angular, you can use Location:
import { Location } from '@angular/common';
// ...
Location.joinWithSlash('beginning', 'end');
Works only on 2 arguments though, so you have to chain calls or write a helper function to do that if needed.
No, you should not use path.join()
to join URL elements.
There's a package for doing that now. So rather than reinvent the wheel, write all your own tests, find bugs, fix them, write more tests, find an edge case where it doesn't work, etc., you could use this package.
https://github.com/jfromaniello/url-join
npm install url-join
var urljoin = require('url-join');
var fullUrl = urljoin('http://www.google.com', 'a', '/b/cd', '?foo=123');
console.log(fullUrl);
Prints:
'http://www.google.com/a/b/cd?foo=123'
When I tried PATH for concatenating url parts I run into problems.
PATH.join
stripes '//' down to '/' and this way invalidates an absolute url (eg. http://... -> http:/...).
For me a quick fix was:
baseurl.replace(/\/$/,"") + '/' + path.replace(/^\//,"") )
or with the solution posted by Colonel Panic:
[pathA.replace(/^\/|\/$/g,""),pathB.replace(/^\/|\/$/g,"")].join("/")