我需要从给定的URL中提取完整的协议、域和端口。例如:
https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181
我需要从给定的URL中提取完整的协议、域和端口。例如:
https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181
当前回答
以下是我使用的解决方案:
const result = `${ window.location.protocol }//${ window.location.host }`;
编辑:
要增加跨浏览器兼容性,请使用以下方法:
const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;
其他回答
Window.location.origin就足以得到相同的。
const full = location.protocol + '//' + location.host;
var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
使用ES6模板文字:
Const url = ' ${location.protocol}//${location.hostname}${location.port?':'+location.port: "} '; . getelementbyid(“结果”)。innerText = url; < div id = "结果" > < / div >
你可以简化为:
Const url = ' ${location.protocol}//${location.host} '; . getelementbyid(“结果”)。innerText = url; < div id = "结果" > < / div >
实际上,window.location.origin在遵循标准的浏览器中工作得很好,但你猜怎么着。IE没有遵循标准。
正因为如此,我在IE、FireFox和Chrome浏览器中使用了这个方法:
var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
但为了将来可能引起冲突的增强,我在“location”对象之前指定了“window”引用。
var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');