@fe-free/tool 1.1.2 → 1.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/package.json +1 -1
- package/src/index.ts +2 -0
- package/src/url/index.ts +48 -0
package/CHANGELOG.md
CHANGED
package/package.json
CHANGED
package/src/index.ts
CHANGED
package/src/url/index.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
type SearchParamsLike = Record<string, any> | URLSearchParams | string;
|
|
2
|
+
|
|
3
|
+
function mergeSearchParams(l, r) {
|
|
4
|
+
const lsp = new URLSearchParams(l);
|
|
5
|
+
const rsp = new URLSearchParams(r);
|
|
6
|
+
|
|
7
|
+
return new URLSearchParams(`${lsp.toString()}&${rsp.toString()}`);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface BuildUrlOptions {
|
|
11
|
+
searchParams?: SearchParamsLike;
|
|
12
|
+
hashSearchParams?: SearchParamsLike;
|
|
13
|
+
}
|
|
14
|
+
// http://xxxx/a/b/c?d=1&e=2?#f/g/h?i=3&j=4
|
|
15
|
+
// path searchParams hash
|
|
16
|
+
function buildURL(url: string, options?: BuildUrlOptions) {
|
|
17
|
+
const { searchParams, hashSearchParams } = options || {};
|
|
18
|
+
|
|
19
|
+
const newURL = new URL(url);
|
|
20
|
+
|
|
21
|
+
// 如果提供则合并
|
|
22
|
+
if (searchParams) {
|
|
23
|
+
const newSP = mergeSearchParams(newURL.searchParams, searchParams);
|
|
24
|
+
newURL.search = `?${newSP.toString()}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (hashSearchParams) {
|
|
28
|
+
// 转换成 URLSearchParams
|
|
29
|
+
const hashSP = new URLSearchParams(hashSearchParams);
|
|
30
|
+
const hash = newURL.hash;
|
|
31
|
+
const index = hash.indexOf('?');
|
|
32
|
+
|
|
33
|
+
// 存在问号
|
|
34
|
+
if (index > -1) {
|
|
35
|
+
// merge
|
|
36
|
+
const newHashSP = mergeSearchParams(hash.slice(index + 1), hashSP);
|
|
37
|
+
newURL.hash = `${hash.slice(0, index)}?${newHashSP.toString()}`;
|
|
38
|
+
}
|
|
39
|
+
// 没有问号
|
|
40
|
+
else {
|
|
41
|
+
newURL.hash = `${hash}?${hashSP.toString()}`;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return newURL.toString();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export { buildURL };
|