What is URL Hash oddities in Javascript?

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 = '#';
var 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?


Answer is:

  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).

0 comments: