有時(shí)候我們需要修改url中某些數(shù)據(jù)宋下,比如換掉url的host梨撞,用a標(biāo)簽來(lái)實(shí)現(xiàn)比較簡(jiǎn)單。
代碼如下:
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標(biāo)簽封裝一個(gè)解析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('/')
};
}
測(cè)試代碼
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"));
結(jié)果如下:
{
"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"]
}