-
-
Save shanecp/e4d4c89f7cca77953e5c to your computer and use it in GitHub Desktop.
Replace a parameter in a query string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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