js实现url
使用 JavaScript 处理 URL
JavaScript 提供了 URL 和 URLSearchParams 对象,可以方便地解析、构造和操作 URL。
解析 URL
const url = new URL('https://example.com/path?name=value#hash');
console.log(url.href); // 完整 URL
console.log(url.origin); // 协议 + 域名 + 端口
console.log(url.protocol); // 协议 (https:)
console.log(url.host); // 域名 + 端口
console.log(url.hostname); // 域名
console.log(url.port); // 端口
console.log(url.pathname); // 路径 (/path)
console.log(url.search); // 查询字符串 (?name=value)
console.log(url.hash); // 哈希 (#hash)
操作查询参数
const url = new URL('https://example.com?foo=bar&baz=qux');
// 获取参数
console.log(url.searchParams.get('foo')); // "bar"
// 设置参数
url.searchParams.set('foo', 'newvalue');
// 添加参数
url.searchParams.append('new', 'param');
// 删除参数
url.searchParams.delete('baz');
// 转换为字符串
console.log(url.toString());
// "https://example.com/?foo=newvalue&new=param"
构造 URL
const url = new URL('https://example.com');
url.pathname = '/new/path';
url.searchParams.set('param', 'value');
console.log(url.href);
// "https://example.com/new/path?param=value"
处理相对 URL
const base = 'https://example.com/base/';
const relative = '../path';
const absolute = new URL(relative, base).href;
console.log(absolute); // "https://example.com/path"
兼容性注意事项
现代浏览器都支持 URL 和 URLSearchParams API。对于旧版浏览器,可能需要使用 polyfill 或手动解析 URL 字符串。

手动解析 URL 的正则表达式方法
function parseUrl(url) {
const pattern = /^(https?:\/\/)?([^\/\?:]+)(:(\d+))?([^?#]*)(\?([^#]*))?(#(.*))?/;
const matches = url.match(pattern);
return {
protocol: matches[1] || '',
host: matches[2] || '',
port: matches[4] || '',
path: matches[5] || '',
query: matches[7] || '',
hash: matches[9] || ''
};
}






