Created
March 26, 2021 11:33
-
-
Save yavgel85/f8e1afe42bfbc8d121a567ab4e97d960 to your computer and use it in GitHub Desktop.
URLJoin #js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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