Replacing Query String Parameters in Javascript
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:
- The parameter name.
- The href.
- 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!
Comments (3)
Leave a Reply
Nice! Handy for those
If you don’t know about jQuery BBQ [1], check that out too. It’s great for those more general query string replacements and reconstruction.
Thanks for sharing this!
[1]: http://benalman.com/code/projects/jquery-bbq/docs/
Link to commentThanks Joe! I’ll definitely check out BBQ.
On another note, I’ll be in Pittsburgh this weekend if you guys want to grab a brew.
Link to commentAw, I’m booked all weekend. Let me know next time you’re around though! @joeyespo
Link to comment