To extract the hostname portion from a URL, we can use the location object that represents information about the current URL. It is the element of the window object and a client-side object.
Syntax:
window.location.propertyname
Example 1: In this example, we will use the self URL, where the code will run to extract the hostname.
html
<!DOCTYPE html>
<html>
<head>
<title>
Get domain from URL
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>URL is:</b>
<script>
document.write(window.location.href);
</script>
<br>
<b>hostname is:</b>
<script>
document.write(window.location.hostname);
</script>
</body>
</html>
|
Output:

Example 2: In this example, we will ask for the URL to the user and then will perform the extraction of the hostname on that URL.
html
<!DOCTYPE html>
<html>
<head>
<title>Extracting URL</title>
</head>
<body>
<h1 style="color: green;">GeeksforGeeks</h1>
<b>Extracting URL</b>
<br><br>
<form name="f1">
<input type="text" name="txt"
placeholder="Paste URL"/>
<input type="button" value="click"
onclick="url2()" />
</form>
<script>
function url2() {
var url3 = document.f1.txt.value;
var j = url3.indexOf("://");
var host = "";
for (i = j + 3; i < url3.length; i++) {
if (url3.charAt(i) != '/') {
host = host + "" + url3.charAt(i);
} else {
break;
}
}
document.write(host);
}
</script>
</body>
</html>
|
Output:

Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
06 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...