Reputation: 449
so lets say i have a url www.hello.com#one
i know i can grab the has value
var hash = window.location.hash;
alert (hash);
but rather then write (i know the below is not propper code):
if var hash = one then set var hashValue to 1
else
if var hash = two then set var hashValue to 2
else etc etc
is there a better way to write this.
Cheers
Upvotes: 0
Views: 771
Reputation: 69915
You can also use switch
block to do this.
switch(location.hash.replace('#', '')){
case "one": newhash = 1;
break;
case "two": newhash = 2;
break;
};
alert (newhash);
Upvotes: 1
Reputation: 5622
Actually the hash returns the hash value including the # sign
So hash='#one' not 'one'. Apart from that you could use a switch case switch(hash) { case '#one': hashVar=1; case '#two': hashVar=2; }
if you are willing to change the hash style to say #tab1 #item1 or simply #1 instead of #one or something, u cud get the number pretty easily
var hash = window.location.hash;//hash=#tab1 say
var number=hash.replace('#tab',"");
alert(number);
That's it. this way, the number can be as large as you want. In the first case you'd have to manually assign the variable for each number
So if there were 100 items you'd have a pretty long list
Upvotes: 1
Reputation: 222268
var map = {
one: 1,
two: 2
};
var hashValue = map[hash.substring(1)];
This will set hashValue to undefined
if hash doesn't exist in the map.
Upvotes: 1