Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Last active December 7, 2017 14:05
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 danieldietrich/864526544d2e1475f28fa00a2f210c1b to your computer and use it in GitHub Desktop.
Save danieldietrich/864526544d2e1475f28fa00a2f210c1b to your computer and use it in GitHub Desktop.
Split an URL into { protocol, host, port, path } using Javascript
function splitUrl(url) {
const parts = url.match(/^(http[s]?):\/\/([^:/]*):?(\d*)\/?(.*)$/i);
if (parts === null) {
throw Error('invalid url: ' + url);
} else {
return {
protocol: parts[1],
host: parts[2],
port: parts[3],
path: (parts[4] === '') ? '' : ('/' + parts[4])
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment