Here is my JavaScript function to manipulate the hash:
var hash = {
get: function(key){
var lh = location.hash;
if(lh.charAt(0) === "#"){
lh = lh.slice(1);
}
var pairs = lh.split("&");
var obj = [];
for(var i = 0; i < pairs.length; i++){
var pair = pairs[i];
if(pair.indexOf("=") > 0){
pair = pair.split("=");
obj[pair[0]] = pair[1];
}else{
obj[pair] = 1;
}
}
return typeof key !== 'undefined' ? obj[key] : obj;
},
set: function(key, value, cb){
var newHash = this.removeKey(key);
if(newHash.length > 1){
newHash += "&";
}
newHash += key + (typeof value != 'undefined' ? "="+value : "");
var url = location.href.split("#")[0] + (newHash !== "#" ? newHash : "");
history.pushState(undefined, document.title, url);
if(cb){
cb();
}
},
del: function(key){
var newHash = this.removeKey(key);
var url = location.href.split("#")[0] + (newHash !== "#" ? newHash : "");
history.pushState(undefined, document.title, url);
},
removeKey: function(key){
var string = location.hash;
if(string.charAt(0) !== "#"){
string = "#" + string;
}
var regex = new RegExp("[#&]"+key+"(=[^&]+|)", 'gi');
string = string.replace(regex, "");
if(string.charAt(0) === "&"){
string = "#" + string.slice(1);
}
return string !== '' ? string : '#';
}
};
I am trying to make it as light as possible.