How to Get Hostname from URL in Javascript

 

In this tutorial, you will learn how to get hostname from url in javascript. Hostname basically represents your domain or subdomain.  Using your own custom logic to extract hostname from url string can be tricky.  That is where URL object comes into play. URL object has property hostname which will return your domain or subdomain.

In the following example, we are simply creating an input field and button.  In the input field, we will enter the url and on click of button, we will extract hostname and display it on the screen.  Please have a look over HTML, CSS, and Javascript code given below.       

 

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <input type="text">
        <button>Get</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>

 

CSS:

body {
    text-align: center;
}

div {
    display: inline-block;
}

input, button {
    display: inline-block;
    padding: 10px 20px;
}

 

Javascript:

let input = document.querySelector('input');
let btnGet = document.querySelector('button');
let result = document.querySelector('h1');

btnGet.addEventListener('click', () => {
    let value = input.value;

    let url = new URL(value);

    result.innerText = url.hostname;
});

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •