Skip to content

Instantly share code, notes, and snippets.

@datchley
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save datchley/766814180850eb10dceb to your computer and use it in GitHub Desktop.

Select an option

Save datchley/766814180850eb10dceb to your computer and use it in GitHub Desktop.
Parse a URL string in it's various parts
function parseUrl(url) {
var _url = (url || window.location.href).match(/^(?:(https?:)\/\/)?([^\?\#\/\:]+)(?::(\d+))?([^\?\#]+)?(\?[^#]+)?(#[^\s]+)?$/),
params = _url[5] || false;
if (!_url.length) {
// couldn't parse url string
return false;
}
if (params && !/^$/.test(params)) {
var pairs = params.replace(/^\?/,'').split('&');
params = {};
// console.log("pairs=%o", pairs);
for (var i=0, l=pairs.length; i<l; i++) {
var keyval = pairs[i].split('=');
params[keyval[0]] = keyval[1];
}
}
return {
source: url,
protocol: _url[1],
host: _url[2],
port: _url[3],
path: _url[4],
query: _url[5],
hash: _url[6],
params: params
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment