-
-
Save AlexKVal/09838292cce14813c39550d3f37b524b to your computer and use it in GitHub Desktop.
Add or update query string parameter
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
// Add / Update a key-value pair in the URL query parameters | |
function updateUrlParameter(uri, key, value) { | |
// remove the hash part before operating on the uri | |
var i = uri.indexOf('#'); | |
var hash = i === -1 ? '' : uri.substr(i); | |
uri = i === -1 ? uri : uri.substr(0, i); | |
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"); | |
var separator = uri.indexOf('?') !== -1 ? "&" : "?"; | |
if (uri.match(re)) { | |
uri = uri.replace(re, '$1' + key + "=" + value + '$2'); | |
} else { | |
uri = uri + separator + key + "=" + value; | |
} | |
return uri + hash; // finally append the hash as well | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment