Join URL segments

JavaScript, String, Regexp · Oct 22, 2020

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'

More like this

  • URLs in JavaScript

    Working with URLs is an essential skill for web developers. This snippet collection covers all the necessary resources to master URLs in JavaScript.

    Collection · 12 snippets

  • Check if absolute URL

    Checks if the given string is an absolute URL.

    JavaScript, String · Oct 20, 2020

  • Map string

    Creates a new string with the results of calling a provided function on every character in the given string.

    JavaScript, String · Oct 21, 2020

  • String to words

    Converts a given string into an array of words.

    JavaScript, String · Oct 22, 2020