Skip to content

Instantly share code, notes, and snippets.

@wescarr
Last active December 11, 2015 02:49
Show Gist options
  • Save wescarr/4533196 to your computer and use it in GitHub Desktop.
Save wescarr/4533196 to your computer and use it in GitHub Desktop.
Parses a URL and returns an object with the same API as window.location with the addition of a "query" attribute which is a hash of query params. Requires underscore.js
function parseUrl(str) {
var link = document.createElement('a');
link.href = str;
// Parse query string. Strip leading ?, decode, and split
var pairs = /^\??(.*)/.exec(decodeURI(link.search))[1].split('&');
// Split pairs and create object from tuples
var query = _.object(_.invoke(pairs, 'split', '='));
// Other url properties to copy
var props = [
'hash',
'host',
'hostname',
'origin',
'pathname',
'port',
'protocol',
'search'
];
// Return parsed URL
return _.extend({query: query}, _.pick(link, props));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment