Created
November 29, 2010 10:43
-
-
Save vrutberg/719814 to your computer and use it in GitHub Desktop.
quick n dirty functions for setting/getting url hash values
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
// function to read the url hash (the part after #), and turns it into an object for serialization | |
var getUrlHash = function() { | |
var tmpPos = location.href.indexOf("#"), hashObj = {}; | |
if(tmpPos !== -1) { | |
var hash = location.href.substring(tmpPos+1, location.href.length); | |
// if it has multiple values (separated by an ampersand), we need to consider that | |
tmpPos = hash.indexOf("&"); | |
if(tmpPos !== -1) { | |
var hashSegments = hash.split("&"); | |
for(var i = 0; i < hashSegments.length; i++) { | |
var kv = hashSegments[i].split("="); | |
hashObj[kv[0]] = kv[1]; | |
} | |
} else { | |
tmpPos = hash.indexOf("="); | |
if(tmpPos !== -1) { | |
var kv = tmpPos.split("="); | |
hashObj[kv[0]] = kv[1]; | |
} | |
} | |
} | |
return hashObj; | |
}; | |
// function to set the url hash based on an object representation | |
var setUrlHash = function(kv) { | |
var hash = []; | |
for(k in kv) { | |
hash.push(k+"="+kv[k]); | |
} | |
var urlHash = "#"+hash.join("&"); | |
// if the current location already has a hash, we need to replace it | |
var hashPos = location.href.indexOf("#"); | |
if(hashPos !== -1) { | |
location.href = location.href.substring(0, hashPos)+urlHash; | |
} | |
else { | |
location.href += urlHash; | |
} | |
}; | |
// helper function for quickly appending/replacing values in the url hash | |
var appendUrlHash = function(kv) { | |
var hashObj = getUrlHash(); | |
for(k in kv) { | |
hashObj[k] = kv[k]; | |
} | |
setUrlHash(hashObj); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment