How to Get and Set URL Parameters with JavaScript

πŸ‘‹ Ciprian on Monday, July 8, 2019 in Blog, JavaScript
Last modified on Monday, July 8, 2019

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

πŸ‘‹ Added by Ciprian on Monday, July 8, 2019 in Blog, JavaScript. Last modified on Monday, July 8, 2019.

Leave a Reply

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy