Last active
December 11, 2015 02:49
-
-
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
This file contains hidden or 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 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