把url的参数转化为对象
方法列举
我也有一直在用的方法,每次开发用到的时候,直接粘贴,非常方便。
1
2
3
4
5
6
7
8parseQueryString(url) { url = url == null ? window.location.href : url let search = url.substring(url.lastIndexOf('?') + 1) if (!search) { return {} } return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}') }
这个方法用了好长时间了。网上我还搜到了其他的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13function getQuery(url) { const index = url.indexOf('?'); const obj = {}; if(index === -1) return obj; const queryStr = url.slice(index + 1); const arr = queryStr.split('&'); for(item of arr) { const keyValue = item.split('='); obj[keyValue[0]] = keyValue[1] } return obj; }
执行一下结果:
1
2
3
4
5let url3 = new URL('https://developer.mozilla.org/zh-CN/docs/Web/API/URL?user=liuk&year=30') parseQueryString(url3.search) {user: 'liuk', year: '30'} getQuery(url3.search) {user: 'liuk', year: '30'}
结果一样。 不会有bug了吧
我们再执行一下另一段代码
1
2
3
4
5
6let url = new URL('https://developer.mozilla.org/zh-CN/docs/Web/API/URL?user="liuk"&list="a"&list="b"&year=30') getQuery(url.search) {user: '%22liuk%22', list: '%22b%22', year: '30'} parseQueryString(url.search) {user: '"liuk"', list: '"b"', year: '30'}
list应该是一个数组的。
一直用的代码也会有问题。
关于get方法传递数组的方式
1
2
3
4http://www.cicode.cn/get?ids=1&ids=2 http://www.cicode.cn/get?ids[0]=1&ids[1]=2 http://www.cicode.cn/get?ids[]=1&ids[]=2 http://www.cicode.cn/get?ids=1,2
URLSearchParams
看一下它的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class URLSearchParams implements Iterable<[string, string]> { constructor(init?: URLSearchParams | string | { [key: string]: string | ReadonlyArray<string> | undefined } | Iterable<[string, string]> | ReadonlyArray<[string, string]>); append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; forEach(callback: (value: string, name: string, searchParams: URLSearchParams) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; keys(): IterableIterator<string>; set(name: string, value: string): void; sort(): void; toString(): string; values(): IterableIterator<string>; [Symbol.iterator](): IterableIterator<[string, string]>; }
1
2
3
4
5
6
7
8
9
10parseQueryString(url) { let ret = {} url = url == null ? window.location.href : url let searchParams:any = new URL(url).searchParams let keys = new Set(searchParams.keys()) keys.forEach((key:any)=>{ ret[key] = searchParams.getAll(key) }) return ret }