Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Created March 26, 2021 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/f8e1afe42bfbc8d121a567ab4e97d960 to your computer and use it in GitHub Desktop.
Save yavgel85/f8e1afe42bfbc8d121a567ab4e97d960 to your computer and use it in GitHub Desktop.
URLJoin #js
// Joins all given URL segments together, then normalizes the resulting URL.
// Use String.prototype.join('/') to combine URL segments.
// Use a series of 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('&', '?');
// Examples
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo');
// 'http://www.google.com/a/b/cd?foo=123&bar=foo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment