如何在JavaScript中解析一个URL

86 阅读1分钟

在本教程中,我们将学习如何使用JavaScript解析一个URL并访问其属性,如主机名、端口、路径名、搜索等。

网址()

在JavaScript中,我们有URL() 构造函数,它接受url 作为第一个参数,然后它返回包含与所提供的URL相关的数据的对象。

例子。

const google = "https://google.com/?q=ss";

const url = new URL(google);

console.log(url);

// url.hostname = "google.com";
// url.pathname = "/"

image.png

在上面的图片中,我们看到的是由URL 构造函数返回的对象。

第二种方法

还有第二种方法,通过使用JavaScript创建一个anchor(<a>)元素来解析url。

const google = "https://google.com/?q=ss";
const a = document.createElement('a');
a.href= google;

现在,我们可以像这样访问url属性。

console.log(a.host);     // "google.com"
console.log(a.href);     // "https://google.com/?q=ss"
console.log(a.protocol); // "https:"
console.log(a.search);   // "?q=ss"