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?
Have you tried this?
if (url.indexOf('#') !== -1) {
// Url contains a #
}
(Where url
is the URL you want to check, obviously.)
window.location.hash
will return the hash identifier
Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.
What most people seem to miss is that those same URL properties are also available to anchor elements:
// To process anchors on click
jQuery('a').click(function () {
if (this.hash) {
// Clicked anchor has a hash
} else {
// Clicked anchor does not have a hash
}
});
// To process anchors without waiting for an event
jQuery('a').each(function () {
if (this.hash) {
// Current anchor has a hash
} else {
// Current anchor does not have a hash
}
});
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
}
This is a simple way to test this for the current page URL:
function checkHash(){
return (location.hash ? true : false);
}
function getHash() {
if (window.location.hash) {
var hash = window.location.hash.substring(1);
if (hash.length === 0) {
return false;
} else {
return hash;
}
} else {
return false;
}
}