'Check URL if it has a specific anchor tag

If a user requests the following address (from another page), I want to scroll down to the contact form area:

http://www.example.com/index.html#contact

How would I check if the URL contains the hash #contact?



Solution 1:[1]

Don't. The browser does that for you. Simply have a name="contact" attribute and the browser will scroll down to that element automatically. for instance:

<h2 name="contact">The contact form is below</h2>
<form> ...

Solution 2:[2]

You can use this simple code to get the URL hash.

var hash = window.location.hash;
if(hash == "#contact") {
    // code
}

Note: this will also return the "#" tag!

Solution 3:[3]

url.match(/#contact$/) should return the matches as an array. Just check if it's not null.

Solution 4:[4]

The hash in the URL will map to the node with the same ID value. So in your case the page will auto scroll to div with an idea of #contact

Solution 5:[5]

you can use

var urlName = document.location.href;
var hash = urlName.split("#").length;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pinoniq
Solution 2 MeSo2
Solution 3 Ins
Solution 4 Llewellyn Collins
Solution 5 MeSo2