views:

33

answers:

1
+2  Q: 

URL Hash oddities

I've noticed some strange behaviour in JS

window.location.hash = '';
var hash = window.location.hash;
alert(hash + ' = ' + hash.length);
//outputs: ' = 0'
window.location.hash = '#';
hash = window.location.hash;
alert(hash + ' = ' + hash.length);
//outputs: ' = 0'
window.location.hash = '_';
hash = window.location.hash;
alert(hash + ' = ' + hash.length);
//outputs: '_ = 2'

basically I want to trigger three conditions

  1. no hash
  2. just hash
  3. hash with text

however it seems like JS doesn't see the difference between example.com/ and example.com/# Also I can't figure out how to remove the hash completely.

Any help?

+2  A: 
  1. Once the hash is set, you cannot remove it altogether (eg, remove the # sign) without causing a page reload; this is normal behavior.

  2. Setting an empty/null hash and setting the hash to the default hash (#) are treated the same; this is just internal behavior. Not sure if all browsers handle it consistently, but IIRC that is the case.

Ultimately if you want to remove the hash completely, you would have to do document.location.href = document.location.href, to reload the page (window.location.reload() would keep the hash).

mway
so there is no case where hash.length = 1
Moak
Nope - it will include the hash character (`#`), and if it's empty or has only the hash character (same to the browser), it reports 0, regardless.
mway
@Moak that is correct. you also cannot tell if `window.location.hash == '#'`. it returns false for both '' and '#'.
contagious
@contagious: An excellent point.@Moak: In such a case you'd obviously just want to do a boolean test before you did any other manipulation/testing (except for equivalence), else you will likely trigger errors.
mway