Skip to content

Instantly share code, notes, and snippets.

@SMotaal
Created December 25, 2018 18:48
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 SMotaal/383f1ee755030fceff1e1ff53a09ca4e to your computer and use it in GitHub Desktop.
Save SMotaal/383f1ee755030fceff1e1ff53a09ca4e to your computer and use it in GitHub Desktop.
URL.resolve Polyfill

URL.resolve(…) Polyfill

Concept

(url => (href, specifier) => {
  try {
    url.href = href;
    if (/^\.{1,2}\/|^\/(?=[^\/]|$)/.test(specifier)) {
      const [, path = '', search = '', hash = ''] = /([^?#]*)([^#]*)(.*)/.exec(specifier);
      const {protocol, host, pathname, href} = url;
      url.protocol = host ? 'http:' : 'file:';
      url.pathname = path[0] === '/' ? path : pathname.replace(/[^/?#]*$/, path);
      url.pathname = url.pathname.replace(/\/+/g, '/');
      url.search = search;
      url.hash = hash;
      url.protocol = protocol;
    }
    return url.href;
  } catch (exception) {
    return exception;
  }
})(new URL('aws://'))('http:domain.com/?x#a', '../a/b/c?y');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment