Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active February 25, 2019 02:48
Show Gist options
  • Save JamieMason/aa949241881122c553652eae7078cdb6 to your computer and use it in GitHub Desktop.
Save JamieMason/aa949241881122c553652eae7078cdb6 to your computer and use it in GitHub Desktop.
An easy way to parse URLs in old Browsers is to use this trick with an <a> Element

Parse a URL using an <a> Element

const parseUrl = url => {
  const a = document.createElement('a');
  a.href = url;
  return {
    hash: a.hash,
    host: a.host,
    hostname: a.hostname,
    href: a.href,
    origin: a.origin,
    pathname: a.pathname,
    port: a.port,
    protocol: a.protocol,
    search: a.search
  };
};

Example

parseUrl('http://what.com:3000/foo/?bar&baz#header');

Outputs:

{
  "hash": "#header",
  "host": "what.com:3000",
  "hostname": "what.com",
  "href": "http://what.com:3000/foo/?bar&baz#header",
  "origin": "http://what.com:3000",
  "pathname": "/foo/",
  "port": "3000",
  "protocol": "http:",
  "search": "?bar&baz"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment