/**
* 比如: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;
}
/**
* 設(shè)置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結(jié)構(gòu)
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
菩鲜,請幫忙指出