鉴于我在下面这一页

http://www.webmail.com/pages/home.aspx

如何用JavaScript检索主机名(“http://www.webmail.com”)?


当前回答

你可以尝试这样做:

1. Get the full URL:

     window.location

2. Get the only protocol:

    window.location.protocol

3. Get the host:

    window.location.host

4. Get the host and protocol:

    window.location.origin

5. Get pathname or directory without protocol and host:

    var url = 'http://www.example.com/somepath/path2/path3/path4';
    
    var pathname = new URL(url).pathname;
    
    alert(pathname); 

其他回答

要获取主机名:location.hostname

但你的例子也在寻找方案,也就是位置。在Chrome中,origin似乎可以做你想做的事情,但在Mozdev文档中却没有提及。你可以用

location.protocol + '//' + location.hostname

如果你也想要端口号(当它不是80时),那么:

location.protocol + '//' + location.host

你可以尝试这样做:

1. Get the full URL:

     window.location

2. Get the only protocol:

    window.location.protocol

3. Get the host:

    window.location.host

4. Get the host and protocol:

    window.location.origin

5. Get pathname or directory without protocol and host:

    var url = 'http://www.example.com/somepath/path2/path3/path4';
    
    var pathname = new URL(url).pathname;
    
    alert(pathname); 

根据您的需要,您可以使用其中一个窗口。位置属性。 在您的问题中,您询问的是主机,可以使用window.location.hostname(例如www.example.com)检索。在你的例子中,你展示了一个叫做原点的东西,它可以使用window.location.origin(例如http://www.example.com)来检索。

var path = window.location.origin + "/";

//result = "http://localhost:60470/"
// will return the host name and port
var host = window.location.host; 

或可能

var host = window.location.protocol + "//" + window.location.host;

或者如果你喜欢串联

var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);

// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);

// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;

如果您有或期望自定义端口,请使用window.location.host而不是window.location.hostname

这应该可以工作:

window.location.hostname