js add url parameter code example

Example 1: js get url parameter

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);

Example 2: js add params to url

function setQueryStringParameter(name, value) {
    const params = new URLSearchParams(window.location.search);
    params.set(name, value);
    window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
}

Example 3: javascript foreach url parameter

// Create a test URLSearchParams object
var searchParams = new URLSearchParams("key1=value1&key2=value2");

// Log the values
searchParams.forEach(function(value, key) {
  console.log(value, key);
});