Created
October 18, 2014 14:07
-
-
Save kanakiyajay/341f33c55cfd7734f885 to your computer and use it in GitHub Desktop.
Update Query String of any url
This file contains 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 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