Skip to content

Latest commit

 

History

History
29 lines (25 loc) · 927 Bytes

URLJoin.md

File metadata and controls

29 lines (25 loc) · 927 Bytes
title tags expertise firstSeen lastUpdated
Join URL segments
string,regexp
advanced
2018-01-16 15:53:03 +0200
2020-10-22 20:24:44 +0300

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('&', '?');
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo');
// 'http://www.google.com/a/b/cd?foo=123&bar=foo'