给定一个 URL 字符串,可以使用下面的方法来解析其中的各种属性:
function parseURL(url) {
//创建一个 a 标签,并将 url 赋值给标签的 href 属性。
const a = document.createElement('a')
a.href = url
return {
source: url,
protocol: a.protocol.replace(':', ''), // 协议
host: a.hostname, // 主机名称
port: a.port, // 端口号
query: a.search, // 查询字符串
params: (function () { // 查询参数
let ret = {},
seg = a.search.replace(/^\?/, '').split('&'),
len = seg.length, i = 0, s
for (; i < len; i++) {
if (!seg[i]) {
continue
}
s = seg[i].split('=')
ret[s[0]] = decodeURIComponent(s[1])
}
return ret
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1], // 文件名
hash: a.hash.replace('#', ''), // 哈希参数
path: a.pathname.replace(/^([^\/])/, '/$1'), // 路径
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1], // 相对路径
segments: a.pathname.replace(/^\//, '').split('/') // 路径片段
}
}
如果只想解析 search params 参数,可以使用下面的方法:
const params = new URLSearchParams(location.search)
const id = params.get('id')
console.log(id)