This handy function adds and modifies a key/value in the URL and was posted by a user Joshua Stewardson:
function updateQueryString(key, value) {
if (!uri) var uri = window.location.hash;
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
};
(I modified it slightly from the original).
It does just what I need except for two things:
One: I am using this for a location hash. I have a function that adds three key-values to the URL on one click and I can't figure out how to prevent it from adding a "?" after the hash, e.g.:
http://localhost/product-list?minify=false#?catId=2&prodId=3&subId=4
Modifying the line
var separator = uri.indexOf('#') !== -1 ? "&" : "#"; // modified
solves the "?" issue, but ignores the first key value and adds it again at the end, e.g.
http://localhost/product-list?minify=false#?catId=1&prodId=2&subId=3&catId=2
Two: I'd like to modify the function so that it removes the key if the value is empty ('') or null, e.g.:
updateQueryString('catId','') || updateQueryString('catId',null)
My RegEx skills are not sharp enough for this. Any help appreciated.
Thanks.
PARTIAL ANSWER
I answered part 1 of my question. Revised code below:
updateQueryString = function (key, value) {
if (!uri) var uri = window.location.hash;
var re = new RegExp("([#|&])" + key + "=.*?(&|$)", "i"); // added "or" and added hash
var separator = uri.indexOf('#') !== -1 ? "&" : "#"; // looks for hash in uri, not ampersand
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
};
If anyone has a suggestion about how to remove the hash parameter if passed an empty or null value, I'm all ears.