Skip to content

Instantly share code, notes, and snippets.

@bg5sbk
Last active December 30, 2015 16:28
Show Gist options
  • Save bg5sbk/7854472 to your computer and use it in GitHub Desktop.
Save bg5sbk/7854472 to your computer and use it in GitHub Desktop.
A query string parser for JavaScript.
QueryString = function(qs){
this.p={};
if(!qs)
qs=location.search;
if(qs) {
var b = qs.indexOf('?');
var e = qs.indexOf('#');
if(b >= 0){
qs = e < 0 ? qs.substr(b + 1) : qs.substring(b + 1,e);
if(qs.length > 0){
qs = qs.replace(/+/g, ' ');
var a = qs.split('&');
for (var i = 0; i < a.length; i++) {
var t = a[i].split('=');
var n = decodeURIComponent(t[0]);
var v = (t.length == 2) ? decodeURIComponent(t[1]) : n;
this.p[n] = v;
}
}
}
}
this.Set = function(name, value){
this.p[name] = value;
return this;
};
this.Get = function(name, def){
var v = this.p[name];
return (v != null) ? v : def;
};
this.Has = function(name) {
return this.p[name] != null;
};
this.ToString = function() {
var r='?';
for (var k in this.p) {
r += encodeURIComponent(k) + '=' + encodeURIComponent(this.p[k]) + '&';
}
return r;
};
};
@bg5sbk
Copy link
Author

bg5sbk commented Dec 8, 2013

Example 1:

var qs = new QueryString(query);

qs.Set("ajaxids", ids)
qs.Set("ajaxsn", new Date())

query = qs.ToString();

Example 2:

query = new QueryString(query).Set("ajaxids", ids).Set("ajaxsn", new Date()).ToString();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment