I am looking to write a piece of javascript that will append a parameter to the current url and then refresh the page - how can I do this?
If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:
const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
function gotoItem( item ){
var url = window.location.href;
var separator = (url.indexOf('?') > -1) ? "&" : "?";
var qs = "item=" + encodeURIComponent(item);
window.location.href = url + separator + qs;
}
More compat version
function gotoItem( item ){
var url = window.location.href;
url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
window.location.href = url;
}
One small bug fix for @yeyo's thoughtful answer above.
Change:
var parameters = parser.search.split(/\?|&/);
To:
var parameters = parser.search.split(/\?|&/);
location.href = location.href + "¶meter=" + value;
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets
This line of JS code takes the link without params (ie before '?'
) and then append params to it.
window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";
The above line of code is appending two params p1
and p2
with respective values 'ABC'
and 'XYZ'
(for better understanding).