Class Act

Back to the shelf

Javascript · Class · ASP.net

JS QueryString class, get and set

A JavaScript class (QueryString) to read a query parameter from the URL and update it without reloading the page.

Example

How to use JS QueryString class, get and set:
After the snippet is in your project, call QueryString.
QueryString();

Notes

set() uses replaceState so no new browser history entry is added. URLSearchParams requires a modern browser. Plus signs in the query string are decoded as spaces.

Code

class QueryString {
    static get(name) {
        var params = new URLSearchParams(window.location.search);
        var value = params.get(name);
        return value === null ? "" : value;
    }

    static set(name, value) {
        var params = new URLSearchParams(window.location.search);
        params.set(name, value);
        var next = window.location.pathname + "?" + params.toString();
        window.history.replaceState(null, "", next);
    }
}