5

Using jQuery, is there a way to distinguish between no hash and an empty hash on the current window.location ?

This is what I call an "empty hash":

http://domain.tld/#

And this is "no hash":

http://domain.tld/
Michaël
  • 3,679
  • 7
  • 39
  • 64
bobylapointe
  • 75
  • 1
  • 5

3 Answers3

7

window.location.hash will return "" for both no hash and empty hash. If you need to make a distinction for some reason, you could split window.location.href by #:

var frag = window.location.href.split("#");

if (frag.length == 1) {
    // No hash
}
else if (!frag[1].length) {
    // Empty hash
}
else {
    // Non-empty hash
}

Or checking for existing hash first, as per your request:

if (window.location.hash) {
    // Non-empty hash
}
else if (window.location.href.split("#").length == 1) {
    // No hash
}
else {
    // Empty hash
}

See also: How to remove the hash from window.location with JavaScript without page refresh?

Community
  • 1
  • 1
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • Is there a way to write it like so: if (the hash is not empty) {} elseif (there is no hash) {} else { // empty hash } ? – bobylapointe Feb 27 '13 at 18:41
  • 1
    @bobylapointe: Sure, though it doesn't make a lot of difference since only one block would be executed each time. See my edit. – Andy E Feb 27 '13 at 19:32
1

You don't need jQuery for this. If you have an empty hash, then all you need to do is check the last character of window.location.href. The following will return true if there is an empty hash:

window.location.href.lastIndexOf('#') === window.location.href.length - 1
Luke Bennett
  • 32,786
  • 3
  • 30
  • 57
0

For those who are interested in a reusable version of Andy E's solution. I made a simple function to get the actual hash-state, as bitwise value.

/**
 * Checks if the location hash is given, empty or not-empty.
 *
 * @param {String} [href] Url to match against, if not given use the current one
 * @returns {Number} An integer to compare with bitwise-operator & (AND)
 */
function getHashState(href) {
  var frag = (href || window.location.href).split('#');
  return frag.length == 1 ? 1 : !frag[1].length ? 2 : 4;
}

You can compare the return values easily with the bitwise AND-operator (&).

if (getHashState() & 1); // no hash
if (getHashState() & 2); // empty hash
if (getHashState() & 4); // no empty hash
yckart
  • 32,460
  • 9
  • 122
  • 129