Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to extract the host name from URL using JavaScript ?

  • Last Updated : 15 Apr, 2020

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

window.location.propertyname

Example 1: In this example, we will use the self URL, where the code will run to extract the hostname.

  • Program:




    <!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 hostname on that URL.

  • Program:




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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!