js 实现urlparse
URL解析的基本概念
URL解析是将URL字符串分解为各个组成部分的过程,包括协议、主机名、路径、查询参数等。JavaScript提供了内置的URL对象来简化这一操作。
使用URL对象解析
JavaScript的URL接口可以方便地解析URL字符串:
const url = new URL('https://example.com/path?name=value#hash');
console.log(url.protocol); // "https:"
console.log(url.hostname); // "example.com"
console.log(url.pathname); // "/path"
console.log(url.search); // "?name=value"
console.log(url.hash); // "#hash"
console.log(url.origin); // "https://example.com"
解析查询参数
URLSearchParams接口可以处理查询字符串:

const params = new URLSearchParams(url.search);
console.log(params.get('name')); // "value"
console.log(params.toString()); // "name=value"
手动解析URL
如果不使用URL对象,可以使用正则表达式手动解析:
function parseUrl(url) {
const pattern = /^(https?:\/\/)?([^\/\?:]+)([\/\?:][^#]*)?(#.*)?$/;
const matches = url.match(pattern);
return {
protocol: matches[1] || '',
host: matches[2] || '',
path: matches[3] || '',
hash: matches[4] || ''
};
}
处理相对URL
URL对象也可以解析相对URL,需要提供base参数:

const relativeUrl = new URL('/path?query=1', 'https://example.com');
console.log(relativeUrl.href); // "https://example.com/path?query=1"
浏览器兼容性
URL和URLSearchParams在现代浏览器中得到广泛支持,但在旧版浏览器中可能需要polyfill。可以使用以下polyfill:
if (!window.URL) {
window.URL = window.URL || window.webkitURL;
}
Node.js环境中的URL解析
Node.js也支持URL模块:
const url = require('url');
const parsed = url.parse('https://example.com/path?query=1');
console.log(parsed.hostname); // "example.com"
注意事项
URL解析时需要注意编码问题,特殊字符需要正确编码和解码。可以使用encodeURIComponent和decodeURIComponent处理查询参数中的特殊字符。






