The difference between an empty hash and no hash

Using jQuery, is there a way to distinguish a hash and an empty hash from the current one window.location?

This is what I call an "empty hash":

http://domain.tld/#

And this is "no hash":

http://domain.tld/
+5
source share
3 answers

window.location.hashwill return ""for both a hash and an empty hash. If you need to make a distinction for any reason, you can divide window.location.hrefby #:

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

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

Or first check the existing hash according to 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 a hash from window.location with JavaScript without refreshing the page?

+7
source

jQuery. , , , window.location.href. true, :

window.location.href.lastIndexOf('#') === window.location.href.length - 1
+1

For those interested in the reusable version of the Andy E. solution, I made a simple function to get the actual hash state as a bit 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 easily compare returned values ​​with the bitwise AND operator ( &).

if (getHashState() & 1); // no hash
if (getHashState() & 2); // empty hash
if (getHashState() & 4); // no empty hash
0
source

All Articles