Skip to content

Instantly share code, notes, and snippets.

@jfsiii
Created February 18, 2010 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfsiii/308019 to your computer and use it in GitHub Desktop.
Save jfsiii/308019 to your computer and use it in GitHub Desktop.
jQuery.extend({
obj2URL: function(obj, url)
{
url = url || '';
var qs = (/\?/.test(url) ? '&' : '?') + $.obj2kvs(obj);
return url + qs;
},
obj2kvs: function(obj)
{
var parts = [],
push = function(key, val){
if (val !== null && (typeof val !== "undefined"))
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
else
parts.push(encodeURIComponent(key) + '=');
},
qs;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
if (val instanceof Array) {
for (var i=0, l=val.length; i<l; i++) { push(key, val[i]); }
} else {
push(key, val);
}
}
}
return parts.join('&');
},
kvs2obj: function (kvs)
{
if (!kvs) return;
var pairs = kvs.replace(/.*\?/, '').split('&'),
obj = {};
$.each(pairs, function (k, v)
{
var pair = v.split('=');
obj[pair[0]] = pair[1];
});
return obj;
},
params: function (str)
{
return $.kvs2obj(str || document.location.search);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment