25

如果我有一个主机名,例如:http ://sample.example.com并且在 Javascript 中window.location.hostname,我会得到“example.com”还是“sample.example.com”?

如果没有,我将如何获得 sample.example.com?

4

10 回答 10

25

是的,window.location.hostname也会给你子域。如果这不起作用,或者其他浏览器不支持,您可以很容易地解析它:

// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];
于 2009-07-29T15:56:22.810 回答
11

It can be done as below:

var subdomain =  window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;
于 2018-01-09T10:32:54.347 回答
11

这对我有用:

var host = window.location.host
var subdomain = host.split('.')[0]
于 2017-08-12T20:06:46.987 回答
5

First of all, it's window.location, not document.location (document.location works in some browsers but it is not standard)

And yes, location.hostname will return the entire domain name, including any subdomains

Read more here

Window Location

于 2009-07-29T15:57:13.497 回答
5

我知道这是一个老问题,但更可靠的答案是捕获所有子域。可能有嵌套的子域,例如https://my.company.website.com. 为了充分捕获所有子域,我认为这是最简单的答案:

// for https://my.company.website.com,
const subdomain = window.location.hostname.split('.').slice(0, -2).join('.');
console.log(subdomain); // "my.company"
于 2020-10-22T20:14:35.423 回答
3

Yes alert(window.location.hostname) will include subdomains like 'www' and 'sample'.

于 2009-07-29T15:58:17.050 回答
3
const subdomain = window.location.hostname.split(".")[0]

window.location.hostname返回字符串包括子域 - 主域 - ltd
因此您可以通过将其转换为数组然后获取第一项来轻松获取第一个单词

于 2020-10-08T12:55:09.200 回答
2

这个片段怎么样。它可能会有所帮助:

var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);
于 2009-07-29T16:05:06.227 回答
2

使用数组解构,您可以这样做:

// window.location.host = "meta.stackoverflow.com"
const [ , , subdomain] = window.location.hostname.split(".").reverse();
// console.log(subdomain);
// "meta"
于 2019-10-16T07:59:05.983 回答
0

我推荐使用 npm 包psl(公共后缀列表)。你可以看看这个链接:npm psl

于 2020-02-29T09:48:08.060 回答