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/
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/
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?
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
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