我需要从给定的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
当前回答
protocol属性设置或返回当前URL的协议,包括冒号(:)。
这意味着如果你只想获得HTTP/HTTPS部分,你可以这样做:
var protocol = window.location.protocol.replace(/:/g,'')
对于域名,您可以使用:
var domain = window.location.hostname;
对于您可以使用的端口:
var port = window.location.port;
请记住,如果端口在URL中不可见,则端口将是空字符串。例如:
http://example.com/将为端口返回“” http://example.com:80/将返回80端口
如果在没有端口使用时需要显示80/443
var port = window.location.port || (protocol === 'https' ? '443' : '80');
其他回答
出于某种原因,所有的答案都是多余的。这就是一切:
window.location.origin
更多细节可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties
Window.location.protocol + '//' + window.location.host
为什么不使用:
let full = window.location.origin
尝试使用正则表达式(Regex),当你想要验证/提取东西或甚至用javascript做一些简单的解析时,它将非常有用。
正则表达式是:
/([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/
演示:
function breakURL(url){
matches = /([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/.exec(url);
foo = new Array();
if(matches){
for( i = 1; i < matches.length ; i++){ foo.push(matches[i]); }
}
return foo
}
url = "https://www.google.co.uk:55699/search?q=http%3A%2F%2F&oq=http%3A%2F%2F&aqs=chrome..69i57j69i60l3j69i65l2.2342j0j4&sourceid=chrome&ie=UTF-8"
breakURL(url); // [https, www.google.co.uk, 55699]
breakURL(); // []
breakURL("asf"); // []
breakURL("asd://"); // []
breakURL("asd://a"); // [asd, a, undefined]
现在你也可以进行验证了。
Window.location.origin就足以得到相同的。