我需要从给定的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
当前回答
为什么不使用:
let full = window.location.origin
其他回答
var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
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 >
尝试使用正则表达式(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]
现在你也可以进行验证了。
首先获取当前地址
var url = window.location.href
然后解析这个字符串
var arr = url.split("/");
你的网址是:
var result = arr[0] + "//" + arr[2]