Adding a parameter to the URL with JavaScript
You can use one of these:
- https://developer.mozilla.org/en-US/docs/Web/API/URL
- https://developer.mozilla.org/en/docs/Web/API/URLSearchParams
Example:
var url = new URL("http://foo.bar/?x=1&y=2");// If your expected result is "http://foo.bar/?x=1&y=2&x=42"url.searchParams.append('x', 42);// If your expected result is "http://foo.bar/?x=42&y=2"url.searchParams.set('x', 42);
A basic implementation which you'll need to adapt would look something like this:
function insertParam(key, value) { key = encodeURIComponent(key); value = encodeURIComponent(value); // kvp looks like ['key1=value1', 'key2=value2', ...] var kvp = document.location.search.substr(1).split('&'); let i=0; for(; i<kvp.length; i++){ if (kvp[i].startsWith(key + '=')) { let pair = kvp[i].split('='); pair[1] = value; kvp[i] = pair.join('='); break; } } if(i >= kvp.length){ kvp[kvp.length] = [key,value].join('='); } // can return this or... let params = kvp.join('&'); // reload page with new params document.location.search = params;}
This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match
the slow regex method I benchmarked against for completions sake (approx +150% slower)
function insertParam2(key,value){ key = encodeURIComponent(key); value = encodeURIComponent(value); var s = document.location.search; var kvp = key+"="+value; var r = new RegExp("(&|\\?)"+key+"=[^\&]*"); s = s.replace(r,"$1"+kvp); if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;}; //again, do what you will here document.location.search = s;}
const urlParams = new URLSearchParams(window.location.search);urlParams.set('order', 'date');window.location.search = urlParams;
.set first agrument is the key, the second one is the value.