How to Get and Set Query Parameters From URL

on in JavaScript DOM, JavaScript Pagination
Last modified on

Here are two ways to get (and set) query parameters from URL. I’ll add some real life examples in order to understand their usage.

Method #1

The URLSearchParams interface defines utility methods to work with the query string of a URL.

Here’s how to get the current page parameter – ⁣pg in our example below – from URL parameters and return to current page from history.back():

// Get current page from URL parameters and return to current pagefrom history.back()
let queryParams = new URLSearchParams(window.location.search),
    page = 1; // Default is 1

if (parseInt(queryParams.get('pg'), 10) > 0) {
    page = queryParams.get('pg');
}

Here’s how to construct the URLSearchParams object instance from the current URL query string. Note that the page variable has been declared prior to setting it up.

// Construct URLSearchParams object instance from current URL querystring
let queryParams = new URLSearchParams(window.location.search);

// Set new or modify existing page value
queryParams.set('pg', page);

// Replace current querystring with the new one
history.replaceState(null, null, "?" + queryParams.toString());

In the example above, I am replacing the current URL with the updated one, in order to build a pagination system.

Method #2

This one uses custom code, specifically tailored for my personal needs.

Here are the getter and setter functions:

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

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

    return params;
}

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

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

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

Here’s how I use it to get the current parameters and change them based on changing a <select> dropdown value. My order parameter has a possible value of price|asc, meaning I’m sorting some elements based on price, ascending.

1. First, I’m getting all URL parameters as an object.

2. Second, I’m getting the order value from my <select> element.

3. Next, I’m updating the parameters object and setting the new URL.

document.getElementById('order').addEventListener('change', () => {
    // Get URL parameters
    let params = getQueryParameters();

    // Get order value and split the values (price|asc)
    let orderParameters = document.getElementById('order').value.split('|'),
        orderBy = orderParameters[0],
        orderDirection = orderParameters[1];

    // Update parameters and set new URL
    params.orderby = orderBy;
    params.order_direction = orderDirection;
    setQueryParameters(params);

    localStorage.setItem('propertySort', document.getElementById('order').value);
});

As the last step, I’m updating a value using localStorage so I can use it later in another part of my code.

Related posts