我计划为同一个网站购买两个域名。根据所使用的域,我计划在页面上提供稍微不同的数据。是否有一种方法可以让我检测页面正在加载的实际域名,以便我知道要将我的内容更改为什么?
我到处找过这样的东西,但大多数都不是我想要的方式。
例如,当使用
document.write(document.location)
在JSFiddle上返回
http://fiddle.jshell.net/_display/
也就是实际的路径。
我计划为同一个网站购买两个域名。根据所使用的域,我计划在页面上提供稍微不同的数据。是否有一种方法可以让我检测页面正在加载的实际域名,以便我知道要将我的内容更改为什么?
我到处找过这样的东西,但大多数都不是我想要的方式。
例如,当使用
document.write(document.location)
在JSFiddle上返回
http://fiddle.jshell.net/_display/
也就是实际的路径。
当前回答
您可以使用它来删除端口号。
var 主机名 = 窗口.位置.主机; var urlWithoutPort = 'https://${hostname}'; console.log(urlWithoutPort);
其他回答
如何:
window.location.hostname
location对象实际上有许多指向URL不同部分的属性
Use
document.write(document.location.hostname)
窗口。Location有很多属性。请看这里的列表。
您可以使用它来删除端口号。
var 主机名 = 窗口.位置.主机; var urlWithoutPort = 'https://${hostname}'; console.log(urlWithoutPort);
如果您只对域名感兴趣,想要忽略子域,那么您需要解析出host和hostname。
下面的代码可以做到这一点:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
http://jsfiddle.net/5U366/4/
如果你对主机名(例如www.beta.example.com)不感兴趣,而是对域名(例如example.com)感兴趣,这适用于有效的主机名:
function getDomainName(hostName)
{
return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}