I needed to update query string parameters in multiple anchor tags after an ajax form submit today; this handy function handled just that.

Javascript

// Update the appropriate href query string parameter
function paramReplace(name, string, value) {
  // Find the param with regex
  // Grab the first character in the returned string (should be ? or &)
  // Replace our href string with our new value, passing on the name and delimeter
  var re = new RegExp("[\\?&]" + name + "=([^&#]*)"),
      delimeter = re.exec(string)[0].charAt(0),
      newString = string.replace(re, delimeter + name + "=" + value);
 
  return newString;
}

You pass the function three arguments, all as strings:

  1. The parameter name.
  2. The href.
  3. The parameter value.

The function will return back the new href string with your parameter updated to the new value. You can see above in the code some notes on the regex and other methods it’s using.

Public Gist here.

Happy Holidays!