我计划为同一个网站购买两个域名。根据所使用的域,我计划在页面上提供稍微不同的数据。是否有一种方法可以让我检测页面正在加载的实际域名,以便我知道要将我的内容更改为什么?

我到处找过这样的东西,但大多数都不是我想要的方式。

例如,当使用

document.write(document.location)

在JSFiddle上返回

http://fiddle.jshell.net/_display/

也就是实际的路径。


当前回答

即使问题是关于域名,接受的解决方案包括子域名(如。调用location.hostname)得到blog.example.com。 为了将来的参考,我建议使用一行程序来只提取域(例如。https://blog.example.com/index.html -> example.com)作为Micheal。

location.hostname.split('.').filter(( _, i) => i < 2).join('.')

小心!当TLD由两部分组成时(例如.co.uk),它可能会崩溃。如果是这样的话,在上面的代码中修改2和3。

其他回答

如果你想在JavaScript中获得域名,只需使用以下代码:

var domain_name = document.location.hostname;
alert(domain_name);

如果你需要web页面的URL路径,这样你就可以访问web URL路径使用这个例子:

var url = document.URL;
alert(url);

结合上面的一些答案,以下是我销毁cookie的有效方法:

  /**
   * Utility method to obtain the domain URI:
   */
  fetchDomainURI() {
    if (window.location.port.length > 0) {
      return window.location.hostname;
    }
    return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
  }

适用于具有端口的IP地址,例如,0.0.0.0:8000等,以及复杂的域,如app.staging.example.com返回。example.com =>允许跨域Cookie设置和销毁。

如果您只对域名感兴趣,想要忽略子域,那么您需要解析出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/

让我们假设你有这样的url路径:

http://localhost:4200/landing?query=1#2

因此,你可以通过位置值为自己服务,如下所示:

window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"

window.location.search: "?query=1"

现在我们可以得出结论,你在寻找:

window.location.hostname

您可以使用它来删除端口号。

var 主机名 = 窗口.位置.主机; var urlWithoutPort = 'https://${hostname}'; console.log(urlWithoutPort);