我计划为同一个网站购买两个域名。根据所使用的域,我计划在页面上提供稍微不同的数据。是否有一种方法可以让我检测页面正在加载的实际域名,以便我知道要将我的内容更改为什么?
我到处找过这样的东西,但大多数都不是我想要的方式。
例如,当使用
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);
}
其他回答
如果你对主机名(例如www.beta.example.com)不感兴趣,而是对域名(例如example.com)感兴趣,这适用于有效的主机名:
function getDomainName(hostName)
{
return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}
你可以很容易地从Javascript中的location object中获得它:
例如,这个页面的URL是:
http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc
然后我们可以通过location对象的以下属性获得准确的域:
location.host = "www.stackoverflow.com"
location.protocol= "http:"
您可以使用以下方法创建完整的域:
location.protocol + "//" + location.host
在这个例子中,哪个返回http://www.stackoverflow.com
我添加这个,我们可以得到完整的URL和路径与location对象的其他属性:
location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
对于我的情况,最好的匹配是window.location.origin
Use
document.write(document.location.hostname)
窗口。Location有很多属性。请看这里的列表。
让我们假设你有这样的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