js 实现urlparse
URL解析的实现方法
在JavaScript中解析URL可以通过多种方式实现,包括使用原生API和手动解析。以下是几种常见的方法:
使用URL API(现代浏览器支持)
现代浏览器提供了内置的URL API,可以方便地解析URL:

const url = new URL('https://example.com:8080/path?query=string#hash');
console.log(url.protocol); // "https:"
console.log(url.hostname); // "example.com"
console.log(url.port); // "8080"
console.log(url.pathname); // "/path"
console.log(url.search); // "?query=string"
console.log(url.hash); // "#hash"
console.log(url.host); // "example.com:8080"
使用document.createElement('a')(兼容旧浏览器)
对于需要兼容旧浏览器的场景,可以使用DOM方法:
function parseUrl(url) {
const a = document.createElement('a');
a.href = url;
return {
protocol: a.protocol,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
search: a.search,
hash: a.hash,
host: a.host
};
}
手动解析URL字符串
如果需要完全自定义的解析逻辑,可以使用正则表达式:

function parseUrlManual(url) {
const pattern = /^(https?:\/\/)?([^\/:]+)(:\d+)?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/;
const match = url.match(pattern);
return match ? {
protocol: match[1] || '',
hostname: match[2] || '',
port: match[3] ? match[3].substring(1) : '',
pathname: match[4] || '/',
search: match[5] || '',
hash: match[6] || ''
} : null;
}
查询参数处理
解析查询参数可以使用URLSearchParams API:
const params = new URLSearchParams('?key1=value1&key2=value2');
console.log(params.get('key1')); // "value1"
console.log(params.toString()); // "key1=value1&key2=value2"
Node.js环境下的URL解析
在Node.js中可以使用内置的url模块:
const url = require('url');
const parsed = url.parse('https://example.com/path?query=string#hash', true);
console.log(parsed.query); // { query: 'string' }
这些方法覆盖了大多数URL解析需求,从简单的现代API到复杂的手动解析方案,可以根据具体需求选择合适的方法。






