Skip to content
Advertisement

How can I add or update a query string parameter?

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:

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement