JavaScript 如何将URL解析为主机名和路径

JavaScript 如何将URL解析为主机名和路径

我们可以解析URL(统一资源定位符)以访问其组件,这可以使用JavaScript中的预定义属性来实现。例如,第一个示例解析当前网页的URL,第二个示例解析预定义的URL。

示例1

此示例解析当前网页的URL。

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

输出:

JavaScript 如何将URL解析为主机名和路径

示例2

此示例解析预定义的URL。

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

输出:

JavaScript 如何将URL解析为主机名和路径

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程