Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:
<script>
function addParam(v) {
window.location.search += '&' + v;
}
</script>
<a href="javascript:addParam('priceMin=300');">add priceMin=300</a>
There is no need to check for ?
as this is already the search
part and you only need to add the param.
If you don't want to even make use of a function you can write as so:
<a href="javascript:location.search+='&priceMin=300';">add priceMin=300</a>
Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search
part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.
Edit:
In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:
- if the parameter already exists, it should be changed.
- if the parameter already exists multiple times, only the changed copy should survive.
- if the parameter already exists, but have no value, the value should be set.
As search
already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search
:
<script>
function setParam(name, value) {
var l = window.location;
/* build params */
var params = {};
var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;
var s = l.search;
for(var r = x.exec(s); r; r = x.exec(s))
{
r[1] = decodeURIComponent(r[1]);
if (!r[2]) r[2] = '%%';
params[r[1]] = r[2];
}
/* set param */
params[name] = encodeURIComponent(value);
/* build search */
var search = [];
for(var i in params)
{
var p = encodeURIComponent(i);
var v = params[i];
if (v != '%%') p += '=' + v;
search.push(p);
}
search = search.join('&');
/* execute search */
l.search = search;
}
</script>
<a href="javascript:setParam('priceMin', 300);">add priceMin=300</a>
This at least is a bit more robust as it can deal with URLs like these:
test.html?a?b&c&test=foo&priceMin=300
Or even:
test.html?a?b&c&test=foo&pri%63eMin=300
Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.