Querystring parsing

Published: 2017-08-05 12:31:47 +0000
Categories: 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


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);

res = parseQSTypeString(qs);
//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);




Querystring, parse, javascript, ecmascript, params, URI, URL, build,

Latest Posts

Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter