Adding A Parameter To The URL With JavaScript
Solution 1:
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);
Solution 2:
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;
}
Solution 3:
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.
Solution 4:
Thank you all for your contribution. I used annakata code and modified to also include the case where there is no query string in the url at all. Hope this would help.
function insertParam(key, value) {
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
document.location.search = '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
}
Solution 5:
This is very simple solution. Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to end, so you can get latest value in your back-end code.
function addParameterToURL(param){
_url = location.href;
_url += (_url.split('?')[1] ? '&':'?') + param;
return _url;
}
Post a Comment for "Adding A Parameter To The URL With JavaScript"