Skip to content

Instantly share code, notes, and snippets.

@bpletzer
Forked from aymanfarhat/urlobject.js
Last active December 18, 2015 08:38
Show Gist options
  • Save bpletzer/5755059 to your computer and use it in GitHub Desktop.
Save bpletzer/5755059 to your computer and use it in GitHub Desktop.
function urlObject(url, options)
{
if ("" === url) return null;
default_options = {'url':url,'unescape':true,'convert_num':true};
if(typeof options !== "object")
options = default_options;
else
{
for(var index in default_options)
{
if(typeof options[index] ==="undefined")
options[index] = default_options[index];
}
}
var a = document.createElement('a');
a.href = options['url'];
url_query = a.search.substring(1);
var vars = url_query.split('&');
var hashVars = a.hash.substr(1).split('&');
function normalizeParams (vars) {
var params = {};
if(vars[0].length > 1)
{
for(var i = 0; i < vars.length; i++)
{
var pair = vars[i].split("=");
var key = (options['unescape'])?unescape(pair[0]):pair[0];
var val = (options['unescape'])?unescape(pair[1]):pair[1];
if(options['convert_num'])
{
if(val.match(/^\d+$/))
val = parseInt(val);
else if(val.match(/^\d+\.\d+$/))
val = parseFloat(val);
}
if(typeof params[key] === "undefined")
params[key] = val;
else if(typeof params[key] === "string")
params[key] = [params[key],val];
else
params[key].push(val);
}
}
return params;
}
var urlObj = {
protocol:a.protocol,
hostname:a.hostname,
host:a.host,
port:a.port,
hash:a.hash.substr(1),
pathname:a.pathname,
search:a.search,
parameters:normalizeParams(vars),
hashParams:normalizeParams(hashVars),
href: a.href
};
return urlObj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment