Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between empty hash and no hash

Tags:

jquery

anchor

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/
like image 884
bobylapointe Avatar asked Feb 27 '13 13:02

bobylapointe


People also ask

How do you create an empty hash?

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

What is Ruby hash New 0?

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.

How do you add to a hash?

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.


2 Answers

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?

like image 129
Andy E Avatar answered Sep 30 '22 15:09

Andy E


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
like image 23
Luke Bennett Avatar answered Sep 30 '22 15:09

Luke Bennett