Last active
December 7, 2017 14:05
-
-
Save danieldietrich/864526544d2e1475f28fa00a2f210c1b to your computer and use it in GitHub Desktop.
Split an URL into { protocol, host, port, path } using Javascript
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
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