Skip to content

Commit d4c6eef

Browse files
urnotzanezangleran
andauthored
getUrlQuery decodeURIComponent属性值 (#39)
* fix: getUrlQuery decodeURIComponent * fix: 0.10.5 * docs: 补充文档 Co-authored-by: zangleran <zangleran@codemao.cn>
1 parent 71baf57 commit d4c6eef

4 files changed

Lines changed: 21 additions & 4 deletions

File tree

docs/functions/addQueryToUrl.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,19 @@ const query = {
4242
};
4343
addQueryToUrl(query); // ?name=doraemon&time=2020
4444
addQueryToUrl(query, ''); // ?name=doraemon&time=2020
45+
```
46+
47+
## 如果参数是个url
48+
那么需要将参数值转义后再加到url上,因为url上有参数的话,我们无法区分这个参数的结束位置是哪里。
49+
```typescript
50+
import { addQueryToUrl } from '@mlz/doraemon';
51+
52+
const url = 'https://da.ithen.cn';
53+
const query = {
54+
name: 'doraemon',
55+
time: 2020,
56+
url: encodeURIComponent('https://da.ithen.cn?name=哆啦A梦'),
57+
};
58+
addQueryToUrl(query); // ?name=doraemon&time=2020&https%3A%2F%2Fda.ithen.cn%3Fname%3D%E5%93%86%E5%95%A6A%E6%A2%A6
59+
addQueryToUrl(query, ''); // ?name=doraemon&time=2020&https%3A%2F%2Fda.ithen.cn%3Fname%3D%E5%93%86%E5%95%A6A%E6%A2%A6
4560
```

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@mlz/doraemon",
3-
"version": "0.10.4",
3+
"version": "0.10.5",
44
"description": "项目常用但lodash又没有的工具函数集合,哆啦A梦般方便实用",
55
"main": "lib/index.js",
66
"module": "es/index.js",

src/addQueryToUrl.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import * as _ from 'lodash';
33

44
import { IObject } from './global';
55

6-
/** 向url字符串追加参数 */
6+
/** 向url字符串追加参数,
7+
* 如果参数是一个url地址,那么需要先进行encodeURIComponent转义一下 */
78
export function addQueryToUrl(query:IObject, url?:string):string {
89
if (url) {
910
if (!_.isString(url)) {

src/getUrlQuery.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as _ from 'lodash';
22

33
import { IObject } from './global';
44

5-
/** 获取url参数 */
5+
/** 获取url参数,被encode的字符会被decode */
66
export const getUrlQuery = (url:string = location.href) => {
77
const result:IObject = {};
88
// 不是string
@@ -22,7 +22,8 @@ export const getUrlQuery = (url:string = location.href) => {
2222
queryStr.split('&').forEach((item) => {
2323
const equalIndex = item.indexOf('=');
2424
if (equalIndex > -1) {
25-
result[item.substring(0, equalIndex)] = item.substring(equalIndex + 1);
25+
const value = item.substring(equalIndex + 1);
26+
result[item.substring(0, equalIndex)] = decodeURIComponent(value);
2627
}
2728
});
2829
return result;

0 commit comments

Comments
 (0)