在JavaScript中从一个URL中获取域名

624 阅读1分钟

在本教程中,我们将介绍如何用JavaScript获取你正在浏览的URL的当前域名。

获取域名

考虑到我们有以下的URL。

https://reactgo.com/tutorials/javascript/

要从上述URL中访问域名,我们可以使用window.location 对象,该对象包含一个hostname 属性,该属性持有域名。

const domainName =  window.location.hostname;

console.log(domainName); // "reactgo.com"

同样地,我们也可以使用document.domain 属性来访问它。

document.domain; // "reactgo.com"

你也可以使用window.origin 属性获得带有协议的域名(如httpshttp )。

window.origin; //  "https://reactgo.com"