Skip to content

Instantly share code, notes, and snippets.

@Elbone
Last active July 12, 2017 06:26
Show Gist options
  • Save Elbone/d61c66c8e785c5272aabfddad7956d1e to your computer and use it in GitHub Desktop.
Save Elbone/d61c66c8e785c5272aabfddad7956d1e to your computer and use it in GitHub Desktop.
Get component parts of a url in js
// From here:
// https://stackoverflow.com/questions/1420881/how-to-extract-base-url-from-a-string-in-javascript/26708573#26708573
const parseUrl = (string, prop) => {
const a = document.createElement('a');
a.setAttribute('href', string);
const {host, hostname, pathname, port, protocol, search, hash} = a;
const origin = `${protocol}//${hostname}${port.length ? `:${port}`:''}`;
return prop ? eval(prop) : {origin, host, hostname, pathname, port, protocol, search, hash}
}
// Examples
parseUrl('http://mysite:5050/pke45#23')
// {origin: "http://mysite:5050", host: "mysite:5050", hostname: "mysite", pathname: "/pke45", port: "5050"…}
parseUrl('http://mysite:5050/pke45#23', 'origin')
// "http://mysite:5050"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment