30秒学会 JavaScript 片段 · 2023年2月8日

30秒学会 JavaScript 片段 – Join URL segments

Joins all given URL segments together, then normalizes the resulting URL.

  • Use Array.prototype.join() to combine URL segments.
  • Use a series of String.prototype.replace() calls with various regular expressions 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'

翻译自:https://www.30secondsofcode.org/js/s/join-url-segments