URL HASH操作
2020-05-21 本文已影响0人
imakan
/**
* 比如:demo.com#test=1&test2=2
* @param key
* @return value
*/
export function getUrlHash(key: string) {
const matches = window.location.hash.match(new RegExp(key + '=([^&]*)'));
if (matches && matches.length) {
return decodeURIComponent(matches[1]);
}
return null;
}
/**
* 设置url hash
* 覆盖原有hash的值并保留原有的hash值
* 比如:#test=1&test2=2
* @param key
* @param value
*/
export function setUrlHash(key: string, value: string) {
// 解析原有的hash值
let rawHash = window.location.hash.substr(1);
let resultHash: string[] = [];
if (rawHash) {
let hashArr = rawHash.split(/&/).reduce((pr, cr) => {
return pr.concat([cr.split(/=/)]);
}, [] as any[]);
let hashMap = new Map(hashArr);
hashMap.set(key, encodeURIComponent(value));
// 还原为url hash结构
for (let [k, v] of hashMap) {
if (v) {
resultHash.push(k + '=' + v);
} else {
resultHash.push(k + '');
}
}
} else {
resultHash.push(key + '=' + encodeURIComponent(value));
}
window.location.hash = resultHash.join('&').toString();
}
如有
bug
,请帮忙指出