Last active
July 12, 2017 06:26
-
-
Save Elbone/d61c66c8e785c5272aabfddad7956d1e to your computer and use it in GitHub Desktop.
Get component parts of a url in js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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