How can you check for a #hash in a URL using JavaScript?
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.
Solution 1:
Simple use of location hash:
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
Solution 2:
if(window.location.hash) {
var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
alert (hash);
// hash found
} else {
// No hash found
}
Solution 3:
Put the following:
<script type="text/javascript">
if (location.href.indexOf("#") != -1) {
// Your code in here accessing the string like this
// location.href.substr(location.href.indexOf("#"))
}
</script>
Solution 4:
If the URI is not the document's location this snippet will do what you want.
var url = 'example.com/page.html#anchor',
hash = url.split('#')[1];
if (hash) {
alert(hash)
} else {
// do something else
}
Solution 5:
Have you tried this?
if (url.indexOf('#') !== -1) {
// Url contains a #
}
(Where url
is the URL you want to check, obviously.)