Skip to content

Instantly share code, notes, and snippets.

@helpse
Last active December 21, 2016 09:29
Show Gist options
  • Save helpse/4d4842c69782b9f94a72 to your computer and use it in GitHub Desktop.
Save helpse/4d4842c69782b9f94a72 to your computer and use it in GitHub Desktop.
/**
* queryString handler
* by Sergio Melendez
*
* Usage:
* url = location.pathname + getQuery().set('foo', 'bar').remove('baz');
*/
function getQuery() {
var data = {};
location.search.substr(1).split('&').forEach(function (q) {
var s = q.split('='),
k = s[0],
v = s[1] && decodeURIComponent(s[1]);
if (k) data[k] = [v];
});
return new function () {
this.data = data;
this.toString = function () { return setQuery(this.data); };
this.set = function (key, val) { this.data[key] = val; return this; };
this.remove = function (key) { delete this.data[key]; return this; }
};
}
function setQuery(data) {
var query = [];
for (var i in data) {
query.push(i.toString() + '=' + data[i].toString());
}
return '?' + query.join('&');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment