Open In App

How to Extract the Host Name from URL using JavaScript?

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Extracting the hostname from a URL using JavaScript means retrieving the domain part from a complete web address. This can be done using JavaScript’s URL object or methods like window.location, which allow easy access to the hostname of a URL.

What is URL?

A URL (Uniform Resource Locator) is the web address used to access resources on the internet, such as webpages, images, or files, through browsers.

Using the hostname property of the current window location

Here we are using JavaScript’s window.location object to extract the full URL and hostname. The window.location.href outputs the current page URL, while window.location.hostname retrieves only the domain part (hostname) of that URL.

Syntax

window.location.propertyname

Example : 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:

Extracting-Hostname

Extracting Hostname

Extracting Hostname Using indexOf and Looping

here we extracts the hostname from a user-provided URL by locating the position of “://” using indexOf(). It then loops through characters starting after “://” until it encounters a “/”, constructing and displaying the extracted hostname on the page.

Syntax

url3.indexOf("://");

Example : 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() {

            let url3 = document.f1.txt.value;

            let j = url3.indexOf("://");

            let 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:

Extracting-Hostname

Extracting Hostname



Next Article

Similar Reads