How to Get the Domain Name in JavaScript
This article will discuss how to get a domain name programmatically during a web page’s execution using JavaScript events and functions.
The Domain Name
We use a domain name to access a website or web page from a client-side application. It is a text form string that maps to an IP address (numeric).
A string that user types into a web browser search to invoke and call a specific website is known as a domain name. For example, delftstack.com
is the domain name for DelftStack.
Example:
let url = 'https://www.delftstack.com/' // delftstack.com is a domain name
Suppose we are developing a website or a web page. And we need to find out and use the current domain name programmatically during the website’s runtime for some circumstances.
In that case, we can deal with it using JavaScript.
Get the Domain Name in JavaScript
Right now, if we open up the browser’s console and source the object window.location.hostname
, we can see the hostname of this page is delftstack.com
.
window.location
is an object in JavaScript that can find the current page URL as a string, and we can redirect our browser to another page.
The property window.location.hostname
will return the internet hostname of the current page. If our webpage is on live domain hosting, we can get the URL using window.location.hostname
.
Syntax:
let hostname = window.location.hostname
Example:
<!DOCTYPE html>
<html>
<body>
<h1>DelftStack learnig</h1>
<h2>JavaScript get domain name example</h2>
<p id="para"></p>
<script>
let result = ''
let removeValue = 'www.'
let domainName = window.location.hostname;
result = domainName.replace(removeValue,'')
document.getElementById("para").innerHTML =
"Current page hostname is: " + result;
</script>
</body>
</html>
Code explanation:
- In the above HTML source, we have used the paragraph element tag
<p></p>
and assigned the Id to that element. - Inside the
<script>
tags, we have declared and initialized thedomainName
variable withwindow.location.hostname
. We will get the complete URL as a string. - Now, to trim that string to find the domain only, we have initialized the variable
removeValue
and assignedwww.
. - We have used that variable in the JavaScript default method
replace()
to removewww.
from the URL and store the final value in theresult
variable. - Finally, with the help of the
document.getElementById()
method, we have displayed theresult
string. - You can save the above source with an HTML extension and see the result, make sure to host that HTML document on a live domain.
With Locally Stored HTML Doc
If you don’t have live domain hosting, you can find the path of your locally stored webpage on your system using window.location.href
. It will return the complete path of your HTML doc.
Syntax:
let pathValue =
window.location.href // file:///C:/Users/username/foldername/filename.html