Javascript to parse query strings and use them…

Ever had a project where you needed to do something based off of a querystring value? I have had to use them to do all sorts of things like, fire a tracking pixel with data from a query string, hide and show content based off of a query string, or simply alter content when certain query strings are present. So while this is not something you will need to do all the time, it is something that will likely crop up in front end development here and there.

So let’s get into some very simple code and snippets to help you with doing this in the future!


Javascript get and use query string code snippet

var qs = {}; // create a new empty object

location.search.substr(1).split("&").forEach(function (pair) { // iterate over query string parts

    if (pair === "") {return;} // make sure there is something in it

    var parts = pair.split("="); // setup the seperator to use for splitting

    // populate object
    qs[parts[0]] = parts[1] &&
        decodeURIComponent(parts[1].replace(/\+/g, " ")); // remove + signs from query parameters just in case
});

if (qs.test) { // check for test key in query string

    // do custom logic code
    console.log('test present'); // display console message if test is present in query string
    console.log(qs.test); // show the value of the test query key

} else { // if test=anything is NOT present in the query string
    console.log('no test present'); // lets show that test is not present in the console window
}

September 18, 2018