How to Get Hostname from URL in Javascript
In this tutorial, you will learn how to get hostname from url in javascript. Hostname represents a domain name assigned to a computer. Each domain name points to a specific IP address.
Whenever you enter a domain name in the navigation bar, the browser sends a request to the DNS provider which resolves it to an IP address and loads the website.
There are various ways to extract a hostname from a URL string. You must have seen most of the solutions on the internet recommend using regex to do so but there is no universal solution that can extract a domain as well as a subdomain from a URL string.
To accomplish our goal, we are going to use a URL
object. This object has a hostname
property that will return a domain or subdomain depending upon the URL string.
In the following example, we will enter a random URL in the input field. Upon click of a button, we will extract the hostname and display it on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 4 elements in the HTML file (
div
,input
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element and theh1
element have“Get”
and“Result”
asinnerText
respectively. TheinnerText
of theh1
element will be updated dynamically using javascript. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!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>
body { text-align: center; } div { display: inline-block; } input, button { display: inline-block; padding: 10px 20px; }
Javascript
- We have selected the
input
,button
, andh1
elements using thedocument.querySelector()
method and stored them in theinput
,btnGet
, andresult
variables respectively. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we are getting the value from the
input
element usingvalue
property and storing it in thevalue
variable. - We are using the URL constructor to create an instance of a
URL
object and we are passing it thevalue
variable as a parameter. TheURL
object is stored in theurl
variable. - We are using the
hostname
property to get the hostname fromurl
and displaying it in theh1
element using theinnerText
property.
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; });