I have some jQuery/JavaScript code that I want to run only when there is a hash (#
) anchor link in a URL. How can you check for this character using JavaScript?
Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location
is true, any attempt to invoke Location
will tell you that it's an illegal constructor. You can still get to things like hash
, query
, protocol
etc by setting your string as the href
property of a DOM anchor element, which will then share all the address properties with window.location
.
Simplest way of doing this is:
var a = document.createElement('a');
a.href = string;
string.hash;
For convenience, I wrote a little library that utilises this to replace the native Location
constructor with one that will take strings and produce window.location
-like objects: Location.js