public
Last active

js :: url query parameter utilities

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
var getQueryParamsAsObject = function (qparamList) {
var qparams = {}, pairs;
if (qparamList) {
pairs = $.map(qparamList.split('&'), function (v) {
var pair = {}, keyVal = v.split('=');
pair[keyVal[0]] = keyVal[1];
return pair;
});
$.each(pairs, function (i, v) {
$.extend(qparams, v);
});
}
return qparams;
};
var toQueryParamList = function (qparamObj) {
var pairs = [];
for(var i in qparamObj) {
if (qparamObj.hasOwnProperty(i)) {
pairs.push(i + '=' + qparamObj[i]);
}
}
return pairs.join('&');
};
var updateQueryParam = function (qparamList, key, val) {
var qparamObj = getQueryParamsAsObject(qparamList);
if (val) {
qparamObj[key] = val;
} else { // deletes key if no val is sent
delete qparamObj[key];
}
return toQueryParamList(qparamObj);
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.