Skip to content

Instantly share code, notes, and snippets.

@shuoros
Last active February 13, 2024 05:33
Show Gist options
  • Save shuoros/4a4431c18d1978b67abc96a1f594dd19 to your computer and use it in GitHub Desktop.
Save shuoros/4a4431c18d1978b67abc96a1f594dd19 to your computer and use it in GitHub Desktop.
Get, Add and Delete URL Parameters in Javascript

Some useful functions to interact with URL parameters without refreshing the whole page.

Get All Parameters

function getParams() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
 }

Add or Update Parameters

It will add the given parameterto url or if currently exist it will update its value

function addParam(key, value) {
    url.searchParams.set(key, value);
    window.history.replaceState(null, null, url);
}

Delete a Parameter

function deleteParam(key) {
    url.searchParams.delete(key);
    window.history.replaceState(null, null, url);
}

Delete all Prameters

function deleteAllParams() {
    for(var [key, value] of url.searchParams.entries()) {
       deleteParam(key);
    }
}
function getParams() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
function addParam(key, value) {
url.searchParams.set(key, value);
window.history.replaceState(null, null, url);
}
function deleteParam(key) {
url.searchParams.delete(key);
window.history.replaceState(null, null, url);
}
function deleteAllParams() {
for(var [key, value] of url.searchParams.entries()) {
deleteParam(key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment