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

Urldecode string (LUA)
FFMPEG Convert YUV444p to YUV420p (BASH)
Forcing FFMPEG to honour segment length in HLS Stream Creator (BASH)
Force CURL to place request to a specific IP (BASH)
Set a variable only if it is undefined (Javascript)
Ignore query string with Nginx caching proxy (NGinx)
Get breakdown of UK and non-UK votes for a Parliamentary Petition (Python)
Decompress Mozilla Firefox jsonlz4 bookmark backup files (Python)
Setting Git author details for a single repo (Git)
Checking Virtual Machine Resource Allocations with Libvirt (BASH)

Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk and snippets.6zdgh5a5e6zpchdz.onion