Dus*_*etz 356 javascript hostname
是否有一个非常简单的方法从完整的URL开始:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
Run Code Online (Sandbox Code Playgroud)
并提取主机部分:
aaa.bbb.ccc.com
Run Code Online (Sandbox Code Playgroud)
必须有一个可靠的JavaScript功能,但我找不到它.
Ami*_*aqi 783
假设您有一个包含此地址的页面:http://sub.domain.com/virtualPath/page.htm.在页面代码中使用以下内容来获得这些结果:
window.location.host:你会得到sub.domain.com:8080或sub.domain.com:80window.location.hostname : 你会得到 sub.domain.comwindow.location.protocol : 你会得到 http:window.location.port:你会得到8080或80window.location.pathname : 你会得到 /virtualPathwindow.location.origin:你会得到http://sub.domain.com*****更新:关于.origin
*****正如ref所述,浏览器兼容性window.location.origin尚不清楚.我已经用chrome检查了它,http://sub.domain.com:port如果端口不是80,http://sub.domain.com那么它返回,如果端口是80.
特别感谢@torazaburo向我提到这一点.
CMS*_*CMS 147
您可以连接位置协议和主机:
var root = location.protocol + '//' + location.host;
Run Code Online (Sandbox Code Playgroud)
对于网址,假设'http://stackoverflow.com/questions'它会返回'http://stackoverflow.com'
n13*_*313 35
使用document.location对象及其host或hostname属性.
alert(document.location.hostname); // alerts "stackoverflow.com"
Run Code Online (Sandbox Code Playgroud)
dan*_*ton 22
有两种方法.第一个是这里的另一个答案的变体,但是这个解释了非默认端口:
function getRootUrl() {
var defaultPorts = {"http:":80,"https:":443};
return window.location.protocol + "//" + window.location.hostname
+ (((window.location.port)
&& (window.location.port != defaultPorts[window.location.protocol]))
? (":"+window.location.port) : "");
}
Run Code Online (Sandbox Code Playgroud)
但我更喜欢这个更简单的方法(适用于任何URI字符串):
function getRootUrl(url) {
return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*cny 18
接受的答案对我不起作用,因为希望能够处理任何仲裁URL,而不仅仅是当前的页面URL.
看看URL对象:
var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol; // "http:"
url.hostname; // "aaa.bbb.ccc.com"
url.pathname; // "/asdf/asdf/sadf.aspx"
url.search; // "?blah"
Run Code Online (Sandbox Code Playgroud)
Sun*_*kya 12
假设您有以下 url 路径:
\nhttp://localhost:4200/landing?query=1#2\nRun Code Online (Sandbox Code Playgroud)\n因此,您可以通过位置值为自己服务,如下所示:
\nwindow.location.hash: "#2"\n\xe2\x80\x8b\nwindow.location.host: "localhost:4200"\n\xe2\x80\x8b\nwindow.location.hostname: "localhost"\n\xe2\x80\x8b\nwindow.location.href: "http://localhost:4200/landing?query=1#2"\n\xe2\x80\x8b\nwindow.location.origin: "http://localhost:4200"\n\xe2\x80\x8b\nwindow.location.pathname: "/landing"\n\xe2\x80\x8b\nwindow.location.port: "4200"\n\xe2\x80\x8b\nwindow.location.protocol: "http:"\n\nwindow.location.search: "?query=1"\nRun Code Online (Sandbox Code Playgroud)\n现在我们可以得出结论,您正在寻找:
\nwindow.location.hostname\nRun Code Online (Sandbox Code Playgroud)\n
使用
window.location.origin
并为:" http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah "
你会得到:http://aaa.bbb.ccc.ddd.com/
尝试
document.location.host
Run Code Online (Sandbox Code Playgroud)
要么
document.location.hostname
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
390035 次 |
| 最近记录: |