-
Notifications
You must be signed in to change notification settings - Fork 11
/
url.js
64 lines (59 loc) · 1.79 KB
/
url.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/** URL工具 **/
import { IsEmptyArray, IsEmptyObject } from "../common/type.js";
/**
* @name URL参数反序列化
*/
function ParseUrlSearch() {
const { search } = location;
return search ? search.replace(/(^\?)|(&$)/g, "").split("&").reduce((t, v) => {
const [key, val] = v.split("=");
t[key] = decodeURIComponent(val);
return t;
}, {}) : {};
}
/**
* @name 删除URL参数
* @param {array} search 参数集合
*/
function RemoveUrlSearch(...search) {
if (IsEmptyArray(search)) return;
const url = location.origin + location.pathname;
const hash = location.hash;
const oldSearch = ParseUrlSearch();
search.forEach(v => Reflect.deleteProperty(oldSearch, v));
const newSearchStr = StringifyUrlSearch(oldSearch);
history.pushState({}, null, url + newSearchStr + hash);
}
/**
* @name 设置URL参数
* @param {object} [search={}] 参数集合
*/
function SetUrlSearch(search = {}) {
if (IsEmptyObject(search)) return;
const url = location.origin + location.pathname;
const hash = location.hash;
const oldSearch = ParseUrlSearch();
const newSearch = Object.assign({}, oldSearch, search);
const newSearchStr = StringifyUrlSearch(newSearch);
history.pushState({}, null, url + newSearchStr + hash);
}
/**
* @name URL参数序列化
* @param {object} [search={}] 参数集合
* @param {boolean} [clear=false] 是否清除假值(undefined、null、""、NaN)
*/
function StringifyUrlSearch(search = {}, clear = false) {
return Object.entries(search).reduce((t, v) => {
if (clear) {
return [undefined, null, "", NaN].includes(v[1]) ? t : `${t}${v[0]}=${encodeURIComponent(v[1])}&`;
} else {
return `${t}${v[0]}=${encodeURIComponent(v[1])}&`;
}
}, IsEmptyObject(search) ? "" : "?").replace(/&$/, "");
}
export {
ParseUrlSearch,
RemoveUrlSearch,
SetUrlSearch,
StringifyUrlSearch
};