如何使用JavaScript解析URL

如何使用JavaScript解析URL

给定一个URL,并且任务是使用JavaScript解析该URL并检索所有相关数据。示例:

URL: https://www.geeksforgeeks.org/courses
When we parse the above URL then we can find
hostname: geeksforgeeks.com
path: /courses

方法1

在这个方法中,我们将使用 createElement() 方法来创建一个HTML元素,一个锚点标签,并使用它来解析给定的URL。

// Store the URL into variable 
var url = "https://geeksforgeeks.org/pathname/?search=query"; 
      
// Created a parser using createElement() method 
var parser = document.createElement("a"); 
parser.href = url; 
      
// Host of the URL 
console.log(parser.host); 
      
// Hostname of the URL 
console.log(parser.hostname ); 
      
// Pathname of URL 
console.log(parser.pathname); 
      
// Search in the URL 
console.log(parser.search );

输出:

geeksforgeeks.org
geeksforgeeks.org
/pathname/
?search=query

方法2

在这种方法中,我们将使用URL()来创建一个新的URL对象,然后用它来解析提供的URL。

// Store the URL into variable 
var url = 
"https://geeksforgeeks.org:3000/pathname/?search=query"; 
      
// Created a URL object using URL() method 
var parser = new URL(url); 
      
// Protocol used in URL 
console.log(parser.protocol); 
      
// Host of the URL 
console.log(parser.host); 
      
// Port in the URL 
console.log(parser.port); 
      
// Hostname of the URL 
console.log(parser.hostname); 
      
// Search in the URL 
console.log(parser.search); 
      
// Search parameter in the URL 
console.log(parser.searchParams);

输出:

https:
geeksforgeeks.org:3000
3000
geeksforgeeks.org
?search=query
search=query

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程