How to Get and Set URL Parameters with JavaScript

on in Methods, Events and Scopes
Last modified on

This is an old script, which helped a lot with the initial phase launching a project on all browsers and devices.

function getQueryParameters() {
    var queryString = location.search.slice(1),
        params = {};

    queryString.replace(/([^=]*)=([^&]*)&*/g, function (_, key, value) {
        params[key] = value;
    });

    return params;
}

function setQueryParameters(params) {
    var query = [],
        key,
        value;

    for (key in params) {
        if (!params.hasOwnProperty(key)) {
            continue;
        }
        value = params[key];
        query.push(key + "=" + value);
    }

    location.search = query.join("&");
}

How to use:

var params = getQueryParameters(),
    selectedParameters = document.getElementById('pd_order').value.split('|'),
    orderBy = selectedParameters[0],
    orderDirection = selectedParameters[1];

params.orderby = orderBy;
params.order_direction = orderDirection;
setQueryParameters(params);

Related posts