-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl params.html
96 lines (91 loc) · 3.5 KB
/
url params.html
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>两种类型的Url参数解析与拼接</title>
</head>
<body>
<h2>两种类型的Url参数解析与拼接</h2>
<script>
const obj = {};
const url =
'https: //www.baidu.com/order/list?orderStatus=1&orderStatus=2&reviewStatus=0¤tPage=1&pageSize=10&orderBy=id%20desc';
// url参数解析
if (url.indexOf('?')) {
const index = url.indexOf('?');
const urlStr = url.substr(index + 1);
const urlArr = urlStr.split('&');
urlArr.forEach(item => {
const i = item.indexOf('=');
if (i) {
const key = item.substring(0, i);
const value = decodeURIComponent(item.substr(i + 1));
if (obj[key]) {
const a = [...obj[key], value];
obj[key] = a;
} else {
obj[key] = value;
}
} else {
const key = item;
obj[key] = true;
}
});
console.log(obj);
}
// url参数拼接
const baseUrl = 'https://www.baidu.com/order/list';
const urlParams = obj;
const arr = [];
for (let key in obj) {
const str = `${key}=${encodeURIComponent(obj[key])}`;
arr.push(str);
}
const paramsStr = `${baseUrl}?${arr.join('&')}`;
console.log(paramsStr);
console.log(url);
</script>
<script>
const obj = {};
const url =
'https://www.baidu.com/order/list?status=1,2,3&type=0¤tPage=1&pageSize=10&orderBy=id';
// url参数解析
if (url.includes('?')) {
const index = url.indexOf('?');
const paramsUrl = url.substr(index + 1);
const paramsArr = paramsUrl.split('&');
paramsArr.forEach(item => {
const i = item.indexOf('=');
if (i) {
const key = item.substr(0, i);
const value = item.substr(i + 1);
if (value.includes(',')) {
// array
obj[key] = value.split(',');
} else {
// string
obj[key] = decodeURIComponent(value);
}
} else {
// bool
const key = item;
obj[key] = true;
}
});
}
console.log(obj);
// url参数拼接
const baseUrl = 'https://www.baidu.com/order/list';
const urlParams = obj;
const arr = [];
for (const key in obj) {
const str = `${key}=${encodeURIComponent(obj[key])}`;
arr.push(str);
}
const paramsStr = `${baseUrl}?${arr.join('&')}`;
console.log(paramsStr);
</script>
</body>
</html>