Get the URL Hostname with JavaScript



In this article, you will learn how to get the URL hostname with JavaScript.

What is the hostname?

Originally, it is the name of a computer connected to the network.
When dealing with JavaScript, it is good to recognize that it is the part up to / at the beginning of the URL.

Location: hostname

The hostname property is a property of the Location object that has information about the current location and contains the string that contains the domain of the URL.

The syntax is below.


Since it is a property of Window.location built in JavaScript, you can use it by writing Window.location.hostname as it is.
Since Window is optional, you can use it by writing location.hostname.

Sample Code

Below is a sample code to get the host name.

let anchor = document.createElement("a");
anchor.href = "";

console.log(anchor.hostname);  //