如何使用window.location获取子域名?
如果我有一个主机名,例如: http://sample.example.com 并且在 Javascript 中我会 window.location.hostname
,我会得到“example.com”还是“sample.example.com”?
如果没有,我怎样才能获得sample.example.com?
If I have a hostname such as: http://sample.example.com and in Javascript I do window.location.hostname
, would I get "example.com" or "sample.example.com"?
If not, how would I be able to get sample.example.com?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
是的,
window.location.hostname
也会为您提供子域名。 如果这不起作用,或者不受其他浏览器支持,您可以很容易地解析它:Yes,
window.location.hostname
will give you subdomains as well. If this isn't working, or isn't supported by some other browser, you could quite easily parse for it:我建议使用 npm 包 psl (公共后缀列表)。 您可以查看此链接:npm psl
I recommend using the npm package psl (Public Suffix List). You can look this link: npm psl
这是分割域部分的简单方法,例如
subdomain.maindomain.extension
It's a simple way to split domain parts like
subdomain.maindomain.extension
子域可以有点,用点分割无效。
你可以检查这个库 https://www.npmjs.com/package/psl
这些是有效的子域。
如果您有服务器,您可以在本地计算机上检查它。 这在我的应用程序中有效
http://dev.test.foo.localhost:3000
Subdomain could have dots, splitting with dot is not valid.
You can check this library https://www.npmjs.com/package/psl
These are valid subdomains.
You can check it in your local machine if you have a server. This is working in my app
http://dev.test.foo.localhost:3000
首先,它是
window.location
,而不是document.location
(document.location
在某些浏览器中有效,但不是标准的)是的,
location.hostname
将返回整个域名,包括任何子域在此处阅读更多信息
窗口位置
First of all, it's
window.location
, notdocument.location
(document.location
works in some browsers but it is not standard)And yes,
location.hostname
will return the entire domain name, including any subdomainsRead more here
Window Location
是的,alert(window.location.hostname) 将包含“www”和“sample”等子域。
Yes alert(window.location.hostname) will include subdomains like 'www' and 'sample'.
这个片段怎么样。 它可能有帮助:
How about this snippet. It might help:
通过数组解构,你可以这样做:
with array destructuring you can do this:
可以按如下方式完成:
It can be done as below:
window.location.hostname 返回字符串包括子域 - 主域 - ltd
因此您可以通过将其转换为数组然后获取第一项来轻松获取第一个单词
window.location.hostname return string include subdomain - main domain - ltd
so you can easily get the first word by converting it to an array then getting first item
这对我有用:
This does the trick for me:
我知道这是一个老问题,但更可靠的答案是捕获所有子域。 可以有嵌套子域,例如
https://my.company.website.com
。 为了充分捕获所有子域,我认为这是最简单的答案:I know this is an old question but a more robust answer would be to capture all subdomains. It's possible to have nested subdomains such as
https://my.company.website.com
. In order to adequately capture all subdomains, I think this is the simplest answer:就我而言,我需要一些更通用的东西,所以我编写了这个函数:
In my case I needed something a little more versaitile so I wrote this function: