巧用a标签解析url

重构旧有项目,遇到的比较有意思的点,对于url的解析,并不单单可以通过字符串分割和正则的方式,通过a标签,可以更快捷的做到某些点。

假设现在要解析的网址 url="https://luckyp.top/alinkurl/?id=1#name=haha";

1
2
3
4
5
6
7
8
9
10
11
12
13
14

const alink = document.createElement("a"); // 创建一个a标签

alink.href = url; // 将url设置为a标签的href属性,

console.log(alink.protocol); // 取协议 ===》https:

console.log(alink.hostname); // 取服务器主机===》luckyp.top

console.log(alinkpathname); // 取查询路径===》/alinkurl

console.log(alink.search); // 取查询参数===》?id=1

console.log(alink.hash); // 取#===》#name=haha
------本文结束 感谢阅读------