Skip to content

Instantly share code, notes, and snippets.

@kanakiyajay
Created October 18, 2014 14:07
Show Gist options
  • Save kanakiyajay/341f33c55cfd7734f885 to your computer and use it in GitHub Desktop.
Save kanakiyajay/341f33c55cfd7734f885 to your computer and use it in GitHub Desktop.
Update Query String of any url
function UpdateQueryString(key, value, url) {
if (!url) url = window.location.href;
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi");
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null)
return url.replace(re, '$1' + key + "=" + value + '$2$3');
else {
var hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
}
else {
if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?',
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
else
return url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment