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? I need a simple catch-all test that would detect URLs like these:
- example.com/page.html#anchor
- example.com/page.html#anotheranchor
Basically something along the lines of:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
If anyone could point me in the right direction, that would be much appreciated.
Here is a simple function that returns
true
orfalse
(has / doesn't have a hashtag):Returns
true
in this case.Based on @jon-skeet's comment.
Simple:
sometimes you get the full query string such as "#anchorlink?firstname=mark"
this is my script to get the hash value:
will return the hash identifier
Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:
Or
Should you need this on a regular string variable and happen to have jQuery around, this should work:
(but its maybe a bit overdone .. )
Have you tried this?
(Where
url
is the URL you want to check, obviously.)