This article will state the method of getting the current domain name (excluding the path) with JavaScript.
How to Get/Fetch the Current Domain Name Using JavaScript?
To fetch the current domain name, JavaScript’s “window.location.hostname” property can be used. Furthermore, you can also define a regex pattern as the argument of the “match()” method to get the domain name of the current page.
For practical demonstration, check out the given examples one by one.
Example 1: Get the Current Domain Name Using “window.location.hostname” Property
You can utilize the “window.location.hostname” property for getting the current domain name with JavaScript:
As a result, the name of the current domain is displayed on the console:
Example 2: Get the Current Domain Name Using Regex
You can also use the Regex to get the domain name of the current page. For that purpose, utilize the “window.location.hostname” property which will return the name of the current hostname and store it in a variable:
Here, the “match()” method can be invoked and pass the defined regex pattern as the argument of this method:
Pass the variable that keeps the regex to the “console.log()” method to show the output on the console:
It can be noticed that the domain name of the current page is displayed on the screen:
You have learned the method for getting the current domain name with JavaScript. Furthermore, you can also fetch the domain’s name by utilizing its URL.
Example 3: Get the Current Domain Name Using Regex
Make an object of “URL()” and pass the URL of the current page to it:
Utilize the “domain.hostname” property to get the domain from the provided URL and store it in a variable:
The “console.log()” method is invoked and “domain” variable is passed as an argument to display the result:
It can be observed that the domain name from the provided URL is fetched:
That’s all about getting the current domain name with JavaScript but not the path.
Conclusion
To get the current domain name with JavaScript, the “window.location.hostname” property can be used. Furthermore, you can also specify a regex pattern as an argument to the “match()” method to get the domain name of the current page. This post has stated the method for getting the current domain name with JavaScript but not the path.