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

问题描述 投票:0回答:13

如果我有一个主机名,例如:http://sample.example.com 并且在 Javascript 中我做

window.location.hostname
,我会得到“example.com”还是“sample.example.com”?

如果没有,我怎么能得到 sample.example.com?

javascript subdomain hostname
13个回答
28
投票

是的,

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

// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];

20
投票

这对我有用:

var host = window.location.host
var subdomain = host.split('.')[0]

13
投票

我知道这是一个老问题,但更可靠的答案是捕获所有子域。可以有嵌套的子域,例如

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"

12
投票

可按以下方式进行:

var subdomain =  window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;

5
投票

首先,它是

window.location
,而不是
document.location
document.location
在某些浏览器中工作,但它不是标准的)

是的,

location.hostname
返回整个域名,包括任何子域

在这里阅读更多

窗口位置


5
投票
const subdomain = window.location.hostname.split(".")[0]

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


3
投票

是的 alert(window.location.hostname) 将包括子域,如“www”和“sample”。


2
投票

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

var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);

1
投票

通过数组解构你可以这样做:

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

0
投票

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


0
投票

这是拆分域部分的简单方法,如
subdomain.maindomain.extension

// Print Subdomain
console.log(window.location.host.split('.')[0]);

// Print  Maindomain
console.log(window.location.host.split('.')[1]);

// Print  extension 
console.log(window.location.host.split('.')[2]);

0
投票

我建议您参考这个有用的备忘单。 资料来源:https://www.samanthaming.com/tidbits/86-window-location-cheatsheet/


0
投票

只需使用下面的代码片段。

/^\w+/.exec(location.hostname)[0]
© www.soinside.com 2019 - 2024. All rights reserved.