Querystring parsing



Published: 2017-08-05 12:31:47 +0000
Categories: Javascript,

Language

Javascript

Description

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

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

License

BSD-3-Clause

Keywords

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

Latest Posts

Remotely backing up PFsense Configuration (BASH)
FFMPEG: Converting RMVB to X264 MP4 (BASH)
Recursively print table (print_r equivalent) (LUA)
Bulk Delete Comments from (Self-Hosted) JIRA Issues (Misc)
Add a static entry to the ARP table (BASH)
SSL Cipher Hex codes to Human Readable Names (Misc)
Convert Ascii to Binary (BASH)
Intercepting Outbound DNS Queries (BASH)
Handle Google Verification files within NGinx Configuration (NGinx)
Getting WhatsApp Rich Snippet Previews Working (Misc)

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