我需要从给定的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: '') }`;
使用ES6 模板字面量:
const url = `${location.protocol}//${location.hostname}${location.port?':'+location.port:''}`;
document.getElementById("result").innerText = url;
<div id="result"></div>
您可以简化为:
const url = `${location.protocol}//${location.host}`;
document.getElementById("result").innerText = url;
<div id="result"></div>
如果你想在JavaScript中验证/提取内容或进行简单的解析,尝试使用正则表达式(Regex),这将非常有用。
正则表达式是:
/([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 http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
var getBasePath = function(url) {
var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
return r ? r[0] : '';
};
适用于所有浏览器的简单答案:
最初的回答。let origin;
if (!window.location.origin) {
origin = window.location.protocol + "//" + window.location.hostname +
(window.location.port ? ':' + window.location.port: '');
}
origin = window.location.origin;
/**
* Get the current URL from `window` context object.
* Will return the fully qualified URL if neccessary:
* getCurrentBaseURL(true, false) // `http://localhost/` - `https://localhost:3000/`
* getCurrentBaseURL(true, true) // `http://www.example.com` - `https://www.example.com:8080`
* getCurrentBaseURL(false, true) // `www.example.com` - `localhost:3000`
*
* @param {boolean} [includeProtocol=true]
* @param {boolean} [removeTrailingSlash=false]
* @returns {string} The current base URL.
*/
export const getCurrentBaseURL = (includeProtocol = true, removeTrailingSlash = false) => {
if (!window || !window.location || !window.location.hostname || !window.location.protocol) {
console.error(
`The getCurrentBaseURL function must be called from a context in which window object exists. Yet, window is ${window}`,
[window, window.location, window.location.hostname, window.location.protocol],
)
throw new TypeError('Whole or part of window is not defined.')
}
const URL = `${includeProtocol ? `${window.location.protocol}//` : ''}${window.location.hostname}${
window.location.port ? `:${window.location.port}` : ''
}${removeTrailingSlash ? '' : '/'}`
// console.log(`The URL is ${URL}`)
return URL
}
窗口位置协议 + '//' + 窗口位置主机
console.log(`${req.protocol}://${req.get('host')}/${req.originalUrl}`);
req.protocol
- 返回所使用的协议(例如 HTTP
)req.get(host)
- 返回带有端口号的主机名(例如 localhost:8080
)
window.location.host
可能不是最佳跨浏览器选择。 - nathanfranke