我计划为同一个网站购买两个域名。根据所使用的域,我计划在页面上提供稍微不同的数据。是否有一种方法可以让我检测页面正在加载的实际域名,以便我知道要将我的内容更改为什么?
我到处找过这样的东西,但大多数都不是我想要的方式。
例如,当使用
document.write(document.location)
在JSFiddle上返回
http://fiddle.jshell.net/_display/
也就是实际的路径。
我计划为同一个网站购买两个域名。根据所使用的域,我计划在页面上提供稍微不同的数据。是否有一种方法可以让我检测页面正在加载的实际域名,以便我知道要将我的内容更改为什么?
我到处找过这样的东西,但大多数都不是我想要的方式。
例如,当使用
document.write(document.location)
在JSFiddle上返回
http://fiddle.jshell.net/_display/
也就是实际的路径。
当前回答
如果你对主机名(例如www.beta.example.com)不感兴趣,而是对域名(例如example.com)感兴趣,这适用于有效的主机名:
function getDomainName(hostName)
{
return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}
其他回答
您可以使用它来删除端口号。
var 主机名 = 窗口.位置.主机; var urlWithoutPort = 'https://${hostname}'; console.log(urlWithoutPort);
如果你想在JavaScript中获得域名,只需使用以下代码:
var domain_name = document.location.hostname;
alert(domain_name);
如果你需要web页面的URL路径,这样你就可以访问web URL路径使用这个例子:
var url = document.URL;
alert(url);
如何:
window.location.hostname
location对象实际上有许多指向URL不同部分的属性
Window.location.hostname是一个好的开始。但是它包含子域,您可能想要删除这些子域。例如,如果主机名是www.example.com,你可能只需要example.com位。
像以往一样,有一些极端的情况会让这个问题变得棘手,例如bbc.co.uk。下面的正则表达式很适合我:
让hostname = window.location.hostname; //删除任何子域名,例如www.example.com -> example.com 让域= hostname.match (/^(?:.*?\.)?([ a-zA-Z0-9{3} \ \ _)。(?:\ w {2, 8} | \ w {2,4} \ \ w{2,4})) /美元)[1]; Console.log ("domain: ", domain);
https://publicsuffix.org/list/
(https://github.com/publicsuffix/list/blob/master/public_suffix_list.dat)
需要正确地解析出所有没有后缀的域,在上面的答案中使用点永远不会完全正确。可以对公共后缀dat文件运行上面的代码样例来实现这一点。
您可以基于此编写自己的代码,或者使用https://www.npmjs.com/package/tldts这样的包
getDomainWithoutSuffix('google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.google'); // returns `google`
getDomainWithoutSuffix('foo.google.co.uk'); // returns `google`
getDomainWithoutSuffix('t.co'); // returns `t`
getDomainWithoutSuffix('fr.t.co'); // returns `t`
getDomainWithoutSuffix('https://user:password@example.co.uk:8080/some/path?and&query#hash'); // returns `example`