String.prototype.join('/')
to combine URL segments.String.prototype.replace()
calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&'
and normalize first parameter delimiter).const URLJoin = (...args) => args .join('/') .replace(/[\/]+/g, '/') .replace(/^(.+):\//, '$1://') .replace(/^file:/, 'file:/') .replace(/\/(\?|&|#[^!])/g, '$1') .replace(/\?/g, '&') .replace('&', '?');
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo');
// 'http://www.google.com/a/b/cd?foo=123&bar=foo'
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️