Last active
August 29, 2015 13:57
-
-
Save westc/9549585 to your computer and use it in GitHub Desktop.
Parses a given URL breaking it out into its parts.
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 (RGX_PLUS, RGX_SLASH, RGX_PARAM, decodeURIComponent, undefined) { | |
/** | |
* @license Copyright 2014 - Chris West - MIT Licensed | |
* | |
* Parses a given URL breaking it out into its parts. | |
* @param {string} opt_url | |
* Optional. The URL to be parsed and broken out into its individual | |
* parts. Defaults to the URL of the current page if not given. | |
* @return {!Object} | |
* Object containing the `href`, `protocol`, `host`, `hostname`, `port`, | |
* `pathname`, `search`, and `hash` for the given URL. In addition the | |
* `params` and `hashParams` are specified in this object. The `params` | |
* is an object containing the URL parameters found in the `search`. The | |
* `hashParams` is an object containing the URL parameters found in the | |
* `hash`. Ordinarily the value of each of the parameters will translated | |
* as strings but in the event that the same parameter is found multiple | |
* times the value will be an array of strings. | |
*/ | |
parseUrl = function (opt_url) { | |
var a = document.createElement('a'); | |
a.href = opt_url == undefined ? location.href : opt_url; | |
return { | |
protocol: a.protocol, | |
hostname: a.hostname, | |
host: a.host, | |
port: a.port, | |
href: a.href, | |
// http://stackoverflow.com/questions/956233/javascript-pathname-ie-quirk | |
pathname: a.pathname.replace(RGX_SLASH, '/$&'), | |
search: a.search, | |
hash: a.hash, | |
params: parseParams(a, 'search'), | |
hashParams: parseParams(a, 'hash') | |
}; | |
}; | |
function parseParams(a, prop) { | |
var params = {}, hasOwnProperty = params.hasOwnProperty; | |
(a[prop] || '') | |
.replace(RGX_PLUS, ' ') | |
.replace(RGX_PARAM, function(m, key, value) { | |
key = decodeURIComponent(key); | |
value = value && decodeURIComponent(value); | |
params[key] = hasOwnProperty.call(params, key) | |
? [].concat(params[key], value) // NB: error without Array | |
: value; | |
}); | |
return params; | |
} | |
})( | |
/\+/g, | |
/^[^\/]/, | |
/[#?&]([^=&]*)(?:=([^&]*))?(?=&|$)/g, | |
decodeURIComponent | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment