Thursday, December 11, 2025
HomeLanguagesJavascriptHow to parse a URL into hostname and path in javascript ?

How to parse a URL into hostname and path in javascript ?

We can parse a URL(Uniform Resource Locator) to access its component and this can be achieved using predefined properties in JavaScript. For Example, the first example parses the URL of the current web page and the second example parses a predefined URL.

Example 1:This example parses the URL of the current web page.

HTML




<body style="text-align:center;">
    <h2 style="color:green;">
        Required URL is:
    </h2>
  
    <p id="para1"></p>
  
    <button onclick="my_function()">
        Parse It
    </button>
  
    <p id="para2"></p>
  
    <p id="para3"></p>
  
    <!--Script to parse the URL of 
        the current web page-->
    <script>
        document.getElementById("para1")
            .innerHTML = window.location.href;
          
        function my_function() {
            document.getElementById("para2")
                .innerHTML = 
        `<h3 style="color:green;">Hostname : </h3>` +
                window.location.hostname;
          
            document.getElementById("para3")
                .innerHTML = 
        `<h3 style="color:green;">Path : </h3>` +
                window.location.pathname;
        }
    </script>
</body>


Output:

Parse a URL into hostname and path

Parse a URL into hostname and path

Example 2 This example parses the predefined URL.

HTML




<body style="text-align: center;">
    <h2 style="color: green;">
        Required URL is:
    </h2>
    <p id="para1"></p>
  
    <button onclick="my_function()">
        Parse It
    </button>
    <p id="para2"></p>
  
    <p id="para3"></p>
  
    <!--Script to parse predefined URL -->
    <script>
        var my_url = new URL(
        "https://write.geeksforgeeks.org/post/");
          
        document.getElementById("para1")
                .innerHTML = my_url;
          
        function my_function() {
            document.getElementById("para2")
                .innerHTML = 
        `<h3 style="color:green;">Hostname : </h3>`
                + my_url.hostname;
          
            document.getElementById("para3")
                .innerHTML = 
        `<h3 style="color:green;">Path : </h3>`
                + my_url.pathname;
        }
    </script>
</body>


Output:

Parse a URL into hostname and path

Parse a URL into hostname and path

RELATED ARTICLES

Most Popular

Dominic
32443 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6813 POSTS0 COMMENTS
Nicole Veronica
11950 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12025 POSTS0 COMMENTS
Shaida Kate Naidoo
6944 POSTS0 COMMENTS
Ted Musemwa
7196 POSTS0 COMMENTS
Thapelo Manthata
6889 POSTS0 COMMENTS
Umr Jansen
6881 POSTS0 COMMENTS