We can use JavaScript to get the domain from the URL of the 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 domain from the URL you see at the top of your browser.

var curr_domain = window.location.host;

console.log(curr_domain);

#Output
daztech.com

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 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 domain from the URL of a webpage.

Categorized in:

JavaScript,

Last Update: February 26, 2024