利用a标签,修改url中某些片段和解析url
2019-06-16 本文已影响0人
指尖跳动
有时候我们需要修改url中某些数据,比如换掉url的host,用a标签来实现比较简单。
代码如下:
function hostReplace(src, newHost) {
let domA = document.createElement('a')
domA.href = src
if (newHost) {
domA.host = newHost
}
return domA.href
}
console.log(hostReplace('https://search.jd.com/search?keyword=%E8%8B%B9%E6%9E%9C&enc=utf-8&qrst=1&stop=1&vt=2&cid2=12221#J_searchWrap','www.baidu.com'))
// https://www.baidu.com/search?keyword=%E8%8B%B9%E6%9E%9C&enc=utf-8&qrst=1&stop=1&vt=2&cid2=12221#J_searchWrap
用a标签封装一个解析URL的方法
function parseURL(url) {
var 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(){
var 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]] = 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('/')
};
}
测试代码
console.log(parseURL("https://search.jd.com/search?keyword=%E6%B0%B4%E6%9E%9C&enc=utf-8&qrst=1&stop=1&vt=2&wq=%E6%B0%B4%E6%9E%9C&stock=1&cid2=12221#J_searchWrap"));
结果如下:
{
"source": "https://search.jd.com/search?keyword=%E6%B0%B4%E6%9E%9C&enc=utf-8&qrst=1&stop=1&vt=2&wq=%E6%B0%B4%E6%9E%9C&stock=1&cid2=12221#J_searchWrap",
"protocol": "https",
"host": "search.jd.com",
"port": "",
"query": "?keyword=%E6%B0%B4%E6%9E%9C&enc=utf-8&qrst=1&stop=1&vt=2&wq=%E6%B0%B4%E6%9E%9C&stock=1&cid2=12221",
"params": {
"keyword": "%E6%B0%B4%E6%9E%9C",
"enc": "utf-8",
"qrst": "1",
"stop": "1",
"vt": "2",
"wq": "%E6%B0%B4%E6%9E%9C",
"stock": "1",
"cid2": "12221"
},
"file": "search",
"hash": "J_searchWrap",
"path": "/search",
"relative": "/search?keyword=%E6%B0%B4%E6%9E%9C&enc=utf-8&qrst=1&stop=1&vt=2&wq=%E6%B0%B4%E6%9E%9C&stock=1&cid2=12221#J_searchWrap",
"segments": ["search"]
}