I’ve been searching for sometime now for a piece of code that will accurately return the hash value in the URL. I originally started by using location.hash, however, this had its faults particularly in the cross browser compatibility department so I thought I would build myself a little function to do the trick.
The returnHash function below simply receives a string input, uses a regular expression on the string to match the last hash and then returns the hash value.
Now for this example there are two small points worth making. I have also used a isNumeric function as I only want to return numeric hashes and I have also removed one from the hash. This is due to the fact that the original purpose of this function was to set the initial start value for a JavaScript Accordion using moo.fx or script.aculo.us for example.
// Returns anchor from link string
function returnHash(a_sLink){
// Check for anchor and select active image from nav
var hash = 0;
if((a_sLink.match(/#(\w.*)/) != null)){
if((isNumeric(a_sLink.match(/#(\w.*)/)[1]) == true)){
hash = a_sLink.match(/#(\w.*)/)[1] - 1;
}
}
return hash;
}
Below is the code used to check if the hash retruned is numeric.
function isNumeric(sText)
{
var validChars = "0123456789";
var isNumber=true;
var char;
for (i = 0; i < sText.length && isNumber == true; i++)
{
char = sText.charAt(i);
if (validChars.indexOf(char) == -1)
{
isNumber = false;
}
}
return isNumber;
}
In part two I will show how I integrated this code into a JavaScript Accordian. It’s not ground breaking code but it’s still handy to have.


No Comment Received
Leave A Reply