js实现url

使用 URL 构造函数解析 URL
const url = new URL('https://example.com/path?query=123#hash');
console.log(url.href); // 完整 URL
console.log(url.origin); // 协议 + 域名 + 端口
console.log(url.protocol); // 协议 (https:)
console.log(url.host); // 域名 + 端口
console.log(url.hostname); // 域名 (example.com)
console.log(url.port); // 端口
console.log(url.pathname); // 路径 (/path)
console.log(url.search); // 查询参数 (?query=123)
console.log(url.hash); // 哈希 (#hash)
获取当前页面 URL
const currentUrl = window.location.href;
console.log(currentUrl);
修改 URL 参数
const url = new URL(window.location.href);
url.searchParams.set('key', 'value'); // 添加/修改参数
window.history.pushState({}, '', url); // 更新浏览器 URL(不刷新页面)
解析查询参数
const params = new URLSearchParams(window.location.search);
console.log(params.get('key')); // 获取单个参数
params.forEach((value, key) => { // 遍历所有参数
console.log(key, value);
});
编码与解码 URL 组件
const encoded = encodeURIComponent('测试'); // %E6%B5%8B%E8%AF%95
const decoded = decodeURIComponent(encoded); // 测试
拼接 URL 路径
const baseUrl = 'https://example.com';
const path = '/api/data';
const fullUrl = new URL(path, baseUrl).href; // https://example.com/api/data
验证 URL 格式
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch {
return false;
}
}
console.log(isValidUrl('https://example.com')); // true