Querystring parsing (Javascript)
A pair of utility functions to handle parsing of querystring like strings in javascript
This may simply be a string rather than the querystring itself, so handles any string where key value pairs are ampersand (&) delimited
The encoder accepts an object, and will generate an & delimited string
Similar To
Details
- Language: Javascript
- License: BSD-3-Clause
Snippet
function parseQSTypeString(qs){
// Strip any leading cruft
qs = qs.replace(/\?/,'').replace(/^#/,'');
var result = {};
var splitele;
// Break the pairs up
var pairs = qs.split('&');
// Iterate over and populate our dict
for (var i=0; i<pairs.length; i++){
splitele = pairs[i].split("=");
// There may be a trailing ampersand. Do nothing
if (splitele[0].length > 0){
result[splitele[0]] = decodeURI(splitele[1]);
}
}
return result;
}
function buildQSTypeString(data){
var qs = '';
for (var key in data){
qs += key + "=" + encodeURI(data[key]) + "&"
}
return qs
}
Usage Example
var data,qs,res;
data = {'foo':'bar','type':1,'withspaces':'this is a string with spaces'};
qs = buildQSTypeString(data);
console.log(qs);
//"foo=bar&type=1&withspaces=this%20is%20a%20string%20with%20spaces&"
res = parseQSTypeString(qs);
console.log(res);
//Object {foo: "bar", type: "1", withspaces: "this is a string with spaces"}
// Or to pass the Querystring from the URL in directly
res = parseQSTypeString(window.location.search);