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?
11 Answers
Solution:
let url = window.location.href;
if (url.indexOf('?') > -1){
url += '¶m=1'
} else {
url += '?param=1'
}
window.location.href = url;
-
1
-
1And you should give a ull example with a variable name and a variable parameter with encodeURIComponent(). May 13, 2011 at 20:41
-
-
14one follow up to this, how can add some logic that if the parameter already exists in a url i update its value rather than add a new parameter?– amateurMay 14, 2011 at 0:36
-
1this will take the anchor (hash value) off the url, if it existed, @amateur you can find a function that does that here: stackoverflow.com/questions/486896/… Aug 21, 2011 at 18:44
Shorter than the accepted answer, doing the same, but keeping it simple:
window.location.search += '¶m=42';
We don't have to alter the entire url, just the query string, known as the search attribute of location.
When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.
-
18For a case where you know this will be the only parameter, you can also set search instead of appending to it:
window.location.search = '?param=42';
Sep 2, 2015 at 17:12 -
What if your url is: www.mysite.com ...then won't it make the url: www.mysite.com¶m=42 which would need the "?" character since its the only parameter in the url. I like @Shlomi Komemi answer as it covers those 2 main scenarios. Jan 10, 2017 at 18:57
-
1@greaterKing the browser adds the question mark, when adding parameters to the search attribute of location. Try it in your browsers console. Jan 11, 2017 at 14:03
-
1My bad @BoFrederiksen you are indeed correct...srry about that. "+=" of coarse...missed that. +1 from me. Jan 11, 2017 at 15:27
-
Will this work in
a
tag? Etc.:<a href="javascript:window.location.search += '¶m=42';">
Mar 20, 2017 at 9:12
Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:
location.href = location.href + "¶meter=" + value;
This will work quite well for the majority of the cases.
However
That's not the correct way to append a parameter to a URL in my opinion.
Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:
https://stackoverflow.com/?¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1
at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?
This is my suggested approach:
function URL_add_parameter(url, param, value){
var hash = {};
var parser = document.createElement('a');
parser.href = url;
var parameters = parser.search.split(/\?|&/);
for(var i=0; i < parameters.length; i++) {
if(!parameters[i])
continue;
var ary = parameters[i].split('=');
hash[ary[0]] = ary[1];
}
hash[param] = value;
var list = [];
Object.keys(hash).forEach(function (key) {
list.push(key + '=' + hash[key]);
});
parser.search = '?' + list.join('&');
return parser.href;
}
With this function one just will have to do the following:
location.href = URL_add_parameter(location.href, 'param', 'value');
-
1Why not just to use :
if(window.location.search.indexOf('¶m=') == -1) {window.location.search += '¶m=1';}
– TOPKATMar 29, 2016 at 21:52 -
2@SébastienGarcia-Roméo Yes that's an interesting approach, and indeed valid, however, there are two reasons as of why the function is programmed in that way. 1. To eliminate existing duplicate parameters. 2. To overwrite the value of an existing parameter. From this point of view, now the use of
indexOf
might introduce unnecessary complexity to the code.– yeyoMar 30, 2016 at 0:50 -
1
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;
-
1I think this is the cleanest method since if you already have params in the url, with the other ones you would be repeating them. Jun 21, 2021 at 14:52
-
1Very nice solution, but the URL API is not supported by Internet Explorer. The good news is, that Internet Explorer 11 will be retired and go out of Microsoft support on June 15, 2022. Feb 17, 2022 at 15:24
location.href = location.href + "¶meter=" + value;
-
6
-
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).
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;
}
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'¶m='+value : _url+'?param='+value;
/*reload the page */
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(/\?|&/);
-
Please post such corrections in a comment or propose and edit. They don't warrant a separate answer.– JJJApr 4, 2019 at 19:02
Try this
var url = ApiUrl(`/customers`);
if(data){
url += '?search='+data;
}
else
{
url += `?page=${page}&per_page=${perpage}`;
}
console.log(url);
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets