We can use JavaScript to get the URL hash of the current page we are on by using the window object and getting the location.hash property of it. So the property window.location.hash will return the current hash part of the URL that you see at the top of your browser. Since this page does not have a hash part in the URL, window.location.hash will return nothing.
Let’s say our URL contained a hash. If you click the link below, you will see #example in the URL.
https://daztech.com/javascript-get-url-hash/#example
var curr_path_url = window.location.hash;
console.log(curr_path_url);
#Output
#example
Using JavaScript to Get the Base URL
We can also use JavaScript to get the base URL of the current page we are on by using the window object and getting the location.base property of it. So the property window.location.base will return the current base URL that you see at the top of your browser.
var curr_base_url = window.location.base;
console.log(curr_base_url);
#Output
//https://daztech.com
Using JavaScript to Get the Host URL
We can also use JavaScript to get the host URL of the current page we are on by using the window object and getting the location.host property of it. So the property window.location.host will return the current host URL that you see at the top of your browser.
var curr_host_url = window.location.host;
console.log(curr_host_url);
#Output
daztech.com
Using JavaScript to Get the Current URL
When working with web browsers, sometimes you may want to get the current URL of the page you are working with after getting that web page with your web driver.
We can easily get the current URL of a web page by accessing the window object and getting it’s location.href property.
var curr_url = window.location.href;
console.log(curr_url);
#Output
//https://daztech.com/javascript-get-host-url/
Hopefully this article has been useful for you to learn how to use JavaScript to get the url hash of a webpage.