With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development.
Advertisement
Answer
I wrote the following function which accomplishes what I want to achieve:
JavaScript
x
11
11
1
function updateQueryStringParameter(uri, key, value) {
2
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
3
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
4
if (uri.match(re)) {
5
return uri.replace(re, '$1' + key + "=" + value + '$2');
6
}
7
else {
8
return uri + separator + key + "=" + value;
9
}
10
}
11