如何使用window.location获取子域名?

33

如果我的主机名是http://sample.example.com,那么在Javascript中使用 window.location.hostname,你会得到 "example.com" 还是 "sample.example.com"?

如果不行,要如何才能获取 "sample.example.com" 呢?

13个回答

1

with array destructuring you can do this:

// window.location.host = "meta.stackoverflow.com"
const [ , , subdomain] = window.location.hostname.split(".").reverse();
// console.log(subdomain);
// "meta"

0

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接