Reading the GET parameters in JavaScript

Today i want to write about the situation, when you need a GET parameter in the JavaScript part, and only there, of your website. As sayed, you will never touch or even read the parameter in the PHP or Ruby part of your code, cause it is only there to get something done in the frontend. Exempli gratia you want to switch to the second jquery tab of the actual site. Lets say you want to do this by the GET parameter “tab”. You add the “?tab=0” (as an IT guy i start to count at zero ;)) to your URL. Now you only have to read this parameter and switch to the correct tab. Therefore a GET parameter reading function was my first idea. You call the function and get a nice key-value-object back, so that you can work with it further. Enough said, lets dive into the code:

function getGETParameters() {
    var parameterString = document.location.search.replace('?','');
    var parametersAsString = parameterString.split('&');

    var parameters = {};

    jQuery.each(parametersAsString, function (index, parameter) {
        var parts = parameter.split('=');

        parameters[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
    });

    return parameters;
}

Do you like this post or the code? Let some kind words here 🙂

If not, let me know what could be improved!

You want me to coach you with your programming or software development skills? Write me a direct email to: i@sebastianbauer.name

You want to hire me? Write a direct email too 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *