Created
August 25, 2017 10:14
-
-
Save haipeng/ddbfad38bcc493f079f021ed3c09ae6b to your computer and use it in GitHub Desktop.
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
var updateUrlQuery = function(url, key, value) { | |
var query = key + '=' + value; | |
var search = ''; | |
var hash = ''; | |
var hashIndex = url.indexOf('#'); | |
if (hashIndex > -1) { | |
hash = url.substring(hashIndex); | |
url = url.substring(0, hashIndex); | |
} | |
var queryIndex = url.indexOf('?'); | |
if (queryIndex > -1) { | |
search = url.substring(queryIndex); | |
url = url.substring(0, queryIndex); | |
} | |
if (!search) { | |
return url + '?' + query + hash; | |
} | |
var reg = new RegExp('([?&])' + key + "(=[^&]+)?", 'g'); | |
if (reg.test(search)) { | |
reg.lastIndex = 0; | |
search = search.replace(reg, "$1" + query); | |
return url + search + hash; | |
} | |
return url + search + '&' + query + hash; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment