Skip to content

Instantly share code, notes, and snippets.

@ecabuk
Forked from niyazpk/pQuery.js
Last active February 6, 2016 00:52
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 ecabuk/0f1328d39ff1cf452086 to your computer and use it in GitHub Desktop.
Save ecabuk/0f1328d39ff1cf452086 to your computer and use it in GitHub Desktop.
Add or update query string parameter
### Add / Update a key-value pair in the URL query parameters ###
updateUrlParameter = (uri, key, value)->
# Remove the hash part before operating on the uri
i = uri.indexOf('#')
hash = if i == -1 then '' else uri.substr(i)
uri = if i == -1 then uri else uri.substr(0, i)
re = new RegExp("([?&])" + key + "=.*?(&|$)", "i")
separator = if uri.indexOf('?') != -1 then "&" else "?"
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
// 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