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/
There are different ways to create a hash : Using new class method: new class method will create an empty hash means there will be no default value for the created hash. Here GFG is the default value. Whenever the key or value doesn't exist in above hash then accessing the hash will return the default value “GFG”.
In short, Hash. new(some_value) sets a default value of some_value for every key that does not exist in the hash, Hash. new {|hash, key| block } creates a new default object for every key that does not exist in the hash, and Hash. new() or {} sets nil for every key.
Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With