Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
REGEX: Parse URL into individual parts (JavaScript: The Good Parts)
REGEX: Parse URL into individual parts (Javascript: The Good Parts)
<script type="text/javascript" language="javascript">
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url= "http://www.ora.com:80/goodparts?q#fragment";
var results = parse_url.exec(url);
var names = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash'];
var blanks = ' ';
var i;
for (i = 0; i < names.length; i += 1){
document.writeln('<strong>' + names[i] + '</strong>: ' +
blanks.substring(names[i].length), results[i] + "<br />");
}
</script>
@dmdmdm

This comment has been minimized.

Copy link

commented May 31, 2015

This regular expression has a good balance between robustness and relative simplicity.
It needs to handle user:password however.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.