Add / Change parameter of URL and redirect to the new URL
Solution 1
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName + "="));
var suffix = url.substring(url.indexOf(paramName + "="));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
window.location.href = url + hash;
}
Call the function above in your onclick event.
Solution 2
Why parse the query string yourself when you can let the browser do it for you?
function changeQS(key, value) {
let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);
location.search = urlParams.toString();
}
Solution 3
All the preivous solution doesn't take in account posibility of the substring in parameter. For example http://xyz?ca=1&a=2 wouldn't select parameter a but ca. Here is function which goes through parameters and checks them.
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0)
{
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?")+1) + params.join("&");
}
else
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
Solution 4
I had a similar situation where I wanted to replace a URL query parameter. However, I only had one param, and I could simply replace it:
window.location.search = '?filter=' + my_filter_value
The location.search
property allows you to get or set the query portion of a URL.
Solution 5
Here's a way of accomplishing this. It takes the param name and param value, and an optional 'clear'. If you supply clear=true, it will remove all other params and just leave the newly added one - in other cases, it will either replace the original with the new, or add it if it's not present in the querystring.
This is modified from the original top answer as that one broke if it replaced anything but the last value. This will work for any value, and preserve the existing order.
function setGetParameter(paramName, paramValue, clear)
{
clear = typeof clear !== 'undefined' ? clear : false;
var url = window.location.href;
var queryString = location.search.substring(1);
var newQueryString = "";
if (clear)
{
newQueryString = paramName + "=" + paramValue;
}
else if (url.indexOf(paramName + "=") >= 0)
{
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
if(newQueryString.length > 0) {newQueryString += "&";}
if(decode(key[0]) == paramName)
{
newQueryString += key[0] + "=" + encodeURIComponent(paramValue);;
}
else
{
newQueryString += key[0] + "=" + key[1];
}
}
}
}
else
{
if (url.indexOf("?") < 0)
newQueryString = "?" + paramName + "=" + paramValue;
else
newQueryString = queryString + "&" + paramName + "=" + paramValue;
}
window.location.href = window.location.href.split('?')[0] + "?" + newQueryString;
}
Related videos on Youtube
Comments
-
Draven almost 4 years
If the
&view-all
parameter does NOT exist in the URL I need to add it to the end of the URL along with a value. If it DOES exist then I need to be able to just change the value without creating a new URL because it might, or might not, have other parameters before it.I found this function but I can't get it to work: https://stackoverflow.com/a/10997390/837705
Here is the code I have using the function above (which I can't get to work): http://jsfiddle.net/Draven/tTPYL/4/
I know how to append the parameter and value already:
<div onclick="javascript: window.location.assign(window.location.href+='&view-all=Yes');">Blah Blah</div>
More Info:
If the URL is
http://www.domain.com/index.php?action=my_action
then the default "&view-all" value would be "Yes" so the URL they would be directed to when they click the button ishttp://www.domain.com/index.php?action=my_action&view-all=Yes
.If the URL is
http://www.domain.com/index.php?action=my_action&view-all=Yes
then when they click the button it would change tohttp://www.domain.com/index.php?action=my_action&view-all=No
EDIT: Please give me examples. I don't know alot of JS, and I just can't think of a way to do it in PHP.
-
Marc over 11 yearsI would suggest generating the correct url with PHP so you don't have to mess around with the current location url...
-
Draven over 11 years@Marc How would you suggest I do it in PHP? I can't think of a way.
-
Draven over 11 years@Tom My JS skills are very bad. Could you give me an example?
-
Tomas Ramirez Sarduy over 11 years@Draven, reading your update, I think Marc is right on this, this is more easy (and secure) using php.
-
Sindre Sorhus over 10 yearspossible duplicate of Change URL parameters
-
-
Draven over 11 yearsI don't see how that would work if there are more parameters after the
action
. It is possible the URL ishttp://www.domain.com/index.php?action=my_action&folder=1&view-all=Yes
-
Marc over 11 yearsSure, you need all of them, but you have them in PHP anyway to display your page?
-
ZurabWeb over 10 yearsIf paramName=paramValue is not in the end of the url string, then the rest of the url string is removed. Example ?view=test&page=2&sort=asc will get switched to ?view=test&page=3 and the sort parameter gets lost. Otherwise the function is very good. Thank you.
-
Nico about 10 years@Piero it's because there is an error in the code : the following line must be rewrite var suffix = url.substring(url.indexOf(paramName)).substring(url.indexOf("=") + 1); by two lines : var suffix = url.substring(url.indexOf(paramName)); suffix = suffix.substring(suffix.indexOf("=") + 1);
-
Nico about 10 years@LajosArpad I have edited your post, and done the correction as I described in my previous comment.
-
Wertisdk almost 10 yearsI fixed a small bug, where the function handles # in the URL incorrectly and sets the parameter at the end of URL where it should be set right before the #. I have put the new function in this pastebin: pastebin.com/3R96LKZu
-
user2602152 over 9 years@Wertisdk Thanks! Your anchor variable is global though, it should be initiated with a var.
-
Wertisdk over 9 years@user2602152 I have amended the pastebin so anchor is declared correctly
-
FLX about 9 yearsFYI it fails when your param is named p : If i want to set p to 'lol' i got http=lol
-
Admin about 8 years@LajosArpad What If I don't want to reload page?
-
Lajos Arpad about 8 years@RohitKhatri, depends on what you want to do instead. If you want to know what would be the URL, then you can return url + hash instead of assigning it to window.location.href and then use the function. As a matter of fact, one could implement a library based on this idea. The answer was meant to cope with the need to set a get parameter and redirect to the URL, but you can deviate that if you need something else.
-
Nabi K.A.Z. almost 8 yearsDon't forgot encode param in the function:
var paramName = encodeURI(paramName);
-
Lajos Arpad almost 8 years@NabiK.A.Z., good point. Let's leave out that from this function, as the paramName and paramValue might already by URI-encoded. Nonetheless, your point is valid and one might decide to do that externally. Maybe the best solution is to create a wrapper, a function which takes those parameters, URI-encodes them and calls setGetParameter
-
Umair Ayub over 7 yearsIt refreshes the entire page, I dont want to refresh page,
-
Lajos Arpad over 7 yearsThen return the result instead of assigning it to window.location.href
-
gdbdable almost 7 yearsthis is as all another solutions cause redirect. Can i change parameter value and stay on that page?
-
Pcs almost 7 yearsOf course you can store URL in variable and change it without redirecting.
-
Sylvain Gantois almost 5 yearsI found a bug in this code, if the parameter is included in another part of the URL it breaks. For instance my parameter is s and url is localhost/index.php?a=0&s=3 , the code above breaks when trying to replace the value of s. To fix it var prefix = url.substring(0, url.indexOf(paramName + "=")); var suffix = url.substring(url.indexOf(paramName + "="));
-
Steve Chamaillard over 3 yearsThis is supported in most browsers too, should be the accepted answer.
-
Jordan over 3 yearsNot supported in IE which is enough for many developers to not consider.