Skip to content

Commit bc9719f

Browse files
committed
新增工具函数方法
1 parent 194b3ae commit bc9719f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/utils/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ export * from './axios-method';
66
export * from './axios-result';
77
export * from './data-type';
88
export * from './error-captured';
9+
export * from './url';

src/utils/url.ts

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { isObject } from './data-type';
2+
3+
/**
4+
* 将一个对象组装成query查询的字符串
5+
* @param data
6+
*/
7+
export const queryParamsJoin = (data: { [propsName: string]: any }): string => {
8+
if (!isObject(data)) {
9+
throw new TypeError(`${JSON.stringify(data)}不是对象类型`);
10+
}
11+
const result: string[] = [];
12+
Object.keys(data).forEach((key) => {
13+
if (data[key]) {
14+
result.push(`${key}=${data[key]}`);
15+
}
16+
});
17+
return `${result.join('&')}`;
18+
};
19+
20+
/**
21+
* @param {string} url url地址
22+
* @param {key} key 需要获取的key
23+
* @return:
24+
* @Description: 根据key从一段url中获取query值
25+
* @Author: 水痕
26+
* @LastEditors: 水痕
27+
* @Date: 2019-08-08 15:20:15
28+
*/
29+
export const getUrlQuery = (
30+
url: {
31+
replace: (
32+
arg0: RegExp,
33+
arg1: (_$0: any, $1: string | number, $2: any) => void,
34+
) => void;
35+
},
36+
key: string,
37+
): string => {
38+
let result: any;
39+
const Oparam: { [propName: string]: any } = {};
40+
// 使用正则去捕获
41+
url.replace(
42+
/[\?&]?(\w+)=(\w+)/g,
43+
(_$0: any, $1: string | number, $2: any) => {
44+
if (Oparam[$1] === void 0) {
45+
Oparam[$1] = $2;
46+
} else {
47+
Oparam[$1] = [].concat(Oparam[$1], $2);
48+
}
49+
},
50+
);
51+
if (key === void 0 || key === '') {
52+
result = Oparam;
53+
} else {
54+
result = Oparam[key] || '';
55+
}
56+
return result;
57+
};

0 commit comments

Comments
 (0)