location.hash property that can get the hash value or set a new value to the current URL. To extract the hash from a URL string, there is a
URL() constructor. It takes the string and returns an object that contains the hash as its property.
hash property that will give you the hash value from the current URL in your browser.
const hash = location.hash; console.log(hash); // Returns "#reviews" if the current URL is https://example.com/post#reviews
This property returns the value including the pound sign (#) from the current URL. If you want to remove the pound sign and get only the value, you can go it using the
const hash = location.hash.substring(1); console.log(hash); // Returns "reviews" if the current URL is https://example.com/post#reviews
When I add the
substring() method with "1" as its parameter, it removes the pound sign (#) from the string. In this way, we receive the actual value from the URL.
Get Hash Value From URL String Using URL() Constructor
When we want to get the hash value from a URL string, the location object will not work. Because this object only contains information about the current URL in the browser.
You need to use the
const url = "https://example.com/post#reviews"; const urlObj = new URL(url); const hash = urlObj.hash; console.log(hash); // #reviews
I am extracting the hash value from the
url string using
URL() constructor. The object we get from this constructor has a
This property will contain the value. It will also return the hash value including the pound sign (#) from the
url string. Now, you can use it in your project.
When you want to get the hash value from the current URL, you will use the
location.hash property. But if you want to extract it from a string, you will use the