如果我有一个主机名,例如:http ://sample.example.com并且在 Javascript 中window.location.hostname,我会得到“example.com”还是“sample.example.com”?
如果没有,我将如何获得 sample.example.com?
如果我有一个主机名,例如:http ://sample.example.com并且在 Javascript 中window.location.hostname,我会得到“example.com”还是“sample.example.com”?
如果没有,我将如何获得 sample.example.com?
是的,window.location.hostname也会给你子域。如果这不起作用,或者其他浏览器不支持,您可以很容易地解析它:
// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];
It can be done as below:
var subdomain = window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;
这对我有用:
var host = window.location.host
var subdomain = host.split('.')[0]
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
我知道这是一个老问题,但更可靠的答案是捕获所有子域。可能有嵌套的子域,例如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"
Yes alert(window.location.hostname) will include subdomains like 'www' and 'sample'.
const subdomain = window.location.hostname.split(".")[0]
window.location.hostname返回字符串包括子域 - 主域 - ltd
因此您可以通过将其转换为数组然后获取第一项来轻松获取第一个单词
这个片段怎么样。它可能会有所帮助:
var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);
使用数组解构,您可以这样做:
// window.location.host = "meta.stackoverflow.com"
const [ , , subdomain] = window.location.hostname.split(".").reverse();
// console.log(subdomain);
// "meta"
我推荐使用 npm 包psl(公共后缀列表)。你可以看看这个链接:npm psl