How to Get and Set URL Parameters with JavaScript

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

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.

Contribute!

Contribute to this article by sharing your opinion on Twitter:

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started
Privacy Policy