我需要从给定的URL中提取完整的协议、域和端口。例如:

https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181

当前回答

const full = location.protocol + '//' + location.host;

其他回答

const full = location.protocol + '//' + location.host;

出于某种原因,所有的答案都是多余的。这就是一切:

window.location.origin

更多细节可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

适用于所有浏览器的简单答案:

let origin;

if (!window.location.origin) {
  origin = window.location.protocol + "//" + window.location.hostname + 
     (window.location.port ? ':' + window.location.port: '');
}

origin = window.location.origin;
console.log(`${req.protocol}://${req.get('host')}/${req.originalUrl}`);

要求的事情。protocol -给出你使用的协议(例如HTTP) get(host) -给出带有端口号的主机名(例如localhost:8080)

使用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 >