Get the URL Hostname with JavaScript | Plantpot

Get the URL Hostname with JavaScript

Web Dev
Sponsored links

In this article, I will introduce 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.

location.hostname

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 = "https://plantpot.works/JavaScript/12345";

console.log(anchor.hostname);  // https://plantpot.works