在JavaScript中,正则表达式(RegExp)是用于匹配字符串中字符组合的模式。查找基本URL是指从一个完整的URL中提取出协议、域名和端口(如果有)部分,不包括路径、查询参数和片段标识符。
使用正则表达式提取基本URL的优势包括:
一个典型URL的结构如下:
protocol://domain:port/path?query#fragment
基本URL只包含protocol://domain:port
部分
以下是几种常见的JavaScript正则表达式来提取基本URL:
function getBaseUrl(url) {
const regex = /^(https?:\/\/[^\/?#]+)(?:[\/?#]|$)/i;
const match = url.match(regex);
return match && match[1];
}
// 示例
console.log(getBaseUrl('https://www.example.com/path/to/page?query=string#fragment'));
// 输出: "https://www.example.com"
function getBaseUrlWithPort(url) {
const regex = /^(https?:\/\/[^\/?#:]+(?::\d+)?)(?:[\/?#]|$)/i;
const match = url.match(regex);
return match && match[1];
}
// 示例
console.log(getBaseUrlWithPort('http://localhost:8080/path'));
// 输出: "http://localhost:8080"
function getFullBaseUrl(url) {
const regex = /^(https?:\/\/[\w\-\.]+(?:\.\w{2,})?(?::\d+)?)(?:[\/?#]|$)/i;
const match = url.match(regex);
return match && match[1];
}
// 示例
console.log(getFullBaseUrl('https://sub.domain.co.uk:3000/path'));
// 输出: "https://sub.domain.co.uk:3000"
原因:URL格式复杂多样,简单的正则可能无法覆盖所有情况 解决方案:使用更全面的正则表达式或使用浏览器内置的URL API
// 使用URL API的替代方案
function getBaseUrlUsingURLAPI(url) {
try {
const urlObj = new URL(url);
return `${urlObj.protocol}//${urlObj.host}`;
} catch (e) {
return null;
}
}
原因:复杂的正则表达式可能导致性能下降 解决方案:简化正则或预编译正则表达式
// 预编译正则表达式
const baseUrlRegex = /^(https?:\/\/[^\/?#]+)(?:[\/?#]|$)/i;
function getBaseUrlOptimized(url) {
const match = baseUrlRegex.exec(url);
return match && match[1];
}
原因:相对URL没有协议和域名部分 解决方案:先转换为绝对URL再处理
function getBaseUrlFromRelative(relativeUrl, base) {
try {
const absoluteUrl = new URL(relativeUrl, base).href;
return getBaseUrlUsingURLAPI(absoluteUrl);
} catch (e) {
return null;
}
}