如果我有一个主机名,例如: http://sample.example.com 和Javascript I做 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];

其他提示

首先,它是 window.location ,而不是 document.location document.location 在某些浏览器中有效,但它不是标准的)

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

在这里阅读更多内容

窗口位置

可以按照以下方式完成:

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

是警报(window.location.hostname)将包含子域名,如'www'和'sample'。

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

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

这对我有用:

var host = window.location.host
var subdomain = host.split('.’)[0]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top