Skip to content

Instantly share code, notes, and snippets.

@haipeng
Created August 25, 2017 10:14
Show Gist options
  • Save haipeng/ddbfad38bcc493f079f021ed3c09ae6b to your computer and use it in GitHub Desktop.
Save haipeng/ddbfad38bcc493f079f021ed3c09ae6b to your computer and use it in GitHub Desktop.
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