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

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

例如,当使用

document.write(document.location)

在JSFiddle上返回

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

也就是实际的路径。


当前回答

如果你想在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设置和销毁。

如果你想要一个完整的域原点,你可以使用这个:

document.location.origin

如果你只希望得到域名,使用can you just this:

document.location.hostname

但你有其他的选择,看看属性在:

document.location
function getDomain(url, subdomain) {
    subdomain = subdomain || false;

    url = url.replace(/(https?:\/\/)?(www.)?/i, '');

    if (!subdomain) {
        url = url.split('.');

        url = url.slice(url.length - 2).join('.');
    }

    if (url.indexOf('/') !== -1) {
        return url.split('/')[0];
    }

    return url;
}

例子

getDomain www.example.com’开通:/ /);/ / example.com getDomain’www.example.com’);/ / example.com getDomain(开通:/ / blog.example.com’,true);/ / blog.example.com getDomain location.href);/ /在…

以前的版本是获得全域(包括子域)。现在它根据偏好来确定正确的域。所以当第二个参数被设为真时它将包含子域,否则它只返回"主域"

如果你对主机名(例如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);