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

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

例如,当使用

document.write(document.location)

在JSFiddle上返回

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

也就是实际的路径。


当前回答

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

document.location.origin

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

document.location.hostname

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

document.location

其他回答

你可以很容易地从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"

即使问题是关于域名,接受的解决方案包括子域名(如。调用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。

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);

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

document.location.origin

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

document.location.hostname

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

document.location

这个函数呢?

window.location.hostname.match(/\w*\.\w*$/gi)[0]

这将只匹配域名,不管它是子域还是主域