Skip to content

Instantly share code, notes, and snippets.

@shanecp
Forked from stinoga/index.js
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanecp/e4d4c89f7cca77953e5c to your computer and use it in GitHub Desktop.
Save shanecp/e4d4c89f7cca77953e5c to your computer and use it in GitHub Desktop.
Replace a parameter in a query string
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 + "=([^&#]*)");
var matches = re.exec(string);
var newString;
if (matches === null) {
// if there are no params, append the parameter
newString = (string.indexOf('?') > 0)? string + '&': string + '?';
newString += name + '=' + value;
} else {
var delimeter = matches[0].charAt(0);
newString = string.replace(re, delimeter + name + "=" + value);
}
return newString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment