The hash value sets or returns an anchor part of a URL beginning with the # symbol. It is often used to create internal links between different sections of a web page.

How do you get the URL hash value for a web page when using JavaScript?

JavaScript has a built-in way to get this information using the Location API interface, which represents the location (URL) of the current web page you're located on. The global Window interface has access to the Location object that can be used via window.location.

Using that interface, you can get the URL hash with this method:


This method will return a USVString containing an initial # character followed by the fragment identifier of the URL.

If the URL doesn't contain a hash value or anchor fragment identifier, the method will return an empty string ("").

Here are some example returned values to expect:

      // Page URL:
      window.location.hash == "#Free-Courses"

      // Page URL:
      window.location.hash == ""

Notice that a URL without a hash fragment identifier will return an empty ("") string.

To quickly test this, open the developer tools in your favorite browser and call the window.location.hash function in the JavaScript console. The URL hash fragment identifier should be logged to the console.

For more information on the browser support for this method, see its MDN web docs page.

Thanks for reading and happy coding!