Answers:
var host = window.location.hostname;
或可能
var host = "http://"+window.location.hostname;
或者如果您喜欢串联
var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.hostname);
http
。使用相对协议。比硬编码更合适。
concat
。例如var a = 1 + 2 + " should be 12";
vs this的concat版本var a = "".concat(1).concat(2).concat(" should be 12");
。使用concat可以为您省去很多麻烦,这+
是计算问题,而不是串联问题。
要获取主机名: location.hostname
但是您的示例也在寻找该方案,因此location.origin
似乎可以在Chrome中实现您想要的功能,但是Mozdev文档中并未提及。你可以用
location.protocol + '//' + location.hostname
如果您还想要端口号(当端口号不是80时),则:
location.protocol + '//' + location.host
您可以使用以下命令获取协议,主机和端口:
window.location.origin
| Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|----------------------------------|-------|-----------------|-------------------|-------|--------------------------------------------|
| (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| 30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | 11 | ? | 7 (possibly earlier, see webkit bug 46558) |
| Android | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|----------------------------------|-------|------------------------|----------|--------------|--------------------------------------------|
| (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| 30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | ? | ? | 7 (possibly earlier, see webkit bug 46558) |
所有浏览器兼容性均来自Mozilla开发人员网络
根据您的需要,可以使用其中一个window.location
属性。在您的问题中,您正在询问主机,可以使用window.location.hostname
(例如www.example.com
)检索主机。在您的示例中,您展示了一种称为origin的东西,可以使用window.location.origin
(例如http://www.example.com
)进行检索。
var path = window.location.origin + "/";
//result = "http://localhost:60470/"
我喜欢这个目的
window.location.href.split("/")[2] == "localhost:17000" //always domain + port
您可以将其应用于任何网址字符串
var url = "http://localhost:17000/sub1/sub2/mypage.html?q=12";
url.split("/")[2] == "localhost:17000"
url.split("/")[url.split("/").length-1] == "mypage.html?q=12"
从url字符串中删除协议,域和路径(相对路径)
var arr = url.split("/");
if (arr.length>3)
"/" + arr.splice(3, arr.length).join("/") == "/sub1/sub2/mypage.html?q=12"