Skip to content

Instantly share code, notes, and snippets.

@augustyip
Created June 11, 2014 09:25
Show Gist options
  • Save augustyip/3dd57bca5a07190d873f to your computer and use it in GitHub Desktop.
Save augustyip/3dd57bca5a07190d873f to your computer and use it in GitHub Desktop.
Adding a parameter to the URL with JavaScript
function addParam(url, param, value) {
var a = document.createElement('a'), regex = /[?&]([^=]+)=([^&]*)/g;
var params = {}, match, str = []; a.href = url; value=value||"";
while (match = regex.exec(a.search))
if (param != match[1]) str.push(match[1] + "=" + match[2]);
str.push(encodeURIComponent(param) + "=" + encodeURIComponent(value));
a.search = (a.search.substring(0,1) == "?" ? "" : "?") + str.join("&");
return a.href;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment