UNPKG

18.9 kBTypeScriptView Raw
1export type ParseOptions = {
2 /**
3 Decode the keys and values. URI components are decoded with [`decode-uri-component`](https://github.com/SamVerschueren/decode-uri-component).
4
5 @default true
6 */
7 readonly decode?: boolean;
8
9 /**
10 @default 'none'
11
12 - `bracket`: Parse arrays with bracket representation:
13
14 ```
15 import queryString from 'query-string';
16
17 queryString.parse('foo[]=1&foo[]=2&foo[]=3', {arrayFormat: 'bracket'});
18 //=> {foo: ['1', '2', '3']}
19 ```
20
21 - `index`: Parse arrays with index representation:
22
23 ```
24 import queryString from 'query-string';
25
26 queryString.parse('foo[0]=1&foo[1]=2&foo[3]=3', {arrayFormat: 'index'});
27 //=> {foo: ['1', '2', '3']}
28 ```
29
30 - `comma`: Parse arrays with elements separated by comma:
31
32 ```
33 import queryString from 'query-string';
34
35 queryString.parse('foo=1,2,3', {arrayFormat: 'comma'});
36 //=> {foo: ['1', '2', '3']}
37 ```
38
39 - `separator`: Parse arrays with elements separated by a custom character:
40
41 ```
42 import queryString from 'query-string';
43
44 queryString.parse('foo=1|2|3', {arrayFormat: 'separator', arrayFormatSeparator: '|'});
45 //=> {foo: ['1', '2', '3']}
46 ```
47
48 - `bracket-separator`: Parse arrays (that are explicitly marked with brackets) with elements separated by a custom character:
49
50 ```
51 import queryString from 'query-string';
52
53 queryString.parse('foo[]', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
54 //=> {foo: []}
55
56 queryString.parse('foo[]=', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
57 //=> {foo: ['']}
58
59 queryString.parse('foo[]=1', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
60 //=> {foo: ['1']}
61
62 queryString.parse('foo[]=1|2|3', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
63 //=> {foo: ['1', '2', '3']}
64
65 queryString.parse('foo[]=1||3|||6', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
66 //=> {foo: ['1', '', 3, '', '', '6']}
67
68 queryString.parse('foo[]=1|2|3&bar=fluffy&baz[]=4', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
69 //=> {foo: ['1', '2', '3'], bar: 'fluffy', baz:['4']}
70 ```
71
72 - `colon-list-separator`: Parse arrays with parameter names that are explicitly marked with `:list`:
73
74 ```
75 import queryString from 'query-string';
76
77 queryString.parse('foo:list=one&foo:list=two', {arrayFormat: 'colon-list-separator'});
78 //=> {foo: ['one', 'two']}
79 ```
80
81 - `none`: Parse arrays with elements using duplicate keys:
82
83 ```
84 import queryString from 'query-string';
85
86 queryString.parse('foo=1&foo=2&foo=3');
87 //=> {foo: ['1', '2', '3']}
88 ```
89 */
90 readonly arrayFormat?:
91 | 'bracket'
92 | 'index'
93 | 'comma'
94 | 'separator'
95 | 'bracket-separator'
96 | 'colon-list-separator'
97 | 'none';
98
99 /**
100 The character used to separate array elements when using `{arrayFormat: 'separator'}`.
101
102 @default ,
103 */
104 readonly arrayFormatSeparator?: string;
105
106 /**
107 Supports both `Function` as a custom sorting function or `false` to disable sorting.
108
109 If omitted, keys are sorted using `Array#sort`, which means, converting them to strings and comparing strings in Unicode code point order.
110
111 @default true
112
113 @example
114 ```
115 import queryString from 'query-string';
116
117 const order = ['c', 'a', 'b'];
118
119 queryString.parse('?a=one&b=two&c=three', {
120 sort: (itemLeft, itemRight) => order.indexOf(itemLeft) - order.indexOf(itemRight)
121 });
122 //=> {c: 'three', a: 'one', b: 'two'}
123 ```
124
125 @example
126 ```
127 import queryString from 'query-string';
128
129 queryString.parse('?a=one&c=three&b=two', {sort: false});
130 //=> {a: 'one', c: 'three', b: 'two'}
131 ```
132 */
133 readonly sort?: ((itemLeft: string, itemRight: string) => number) | false;
134
135 /**
136 Parse the value as a number type instead of string type if it's a number.
137
138 @default false
139
140 @example
141 ```
142 import queryString from 'query-string';
143
144 queryString.parse('foo=1', {parseNumbers: true});
145 //=> {foo: 1}
146 ```
147 */
148 readonly parseNumbers?: boolean;
149
150 /**
151 Parse the value as a boolean type instead of string type if it's a boolean.
152
153 @default false
154
155 @example
156 ```
157 import queryString from 'query-string';
158
159 queryString.parse('foo=true', {parseBooleans: true});
160 //=> {foo: true}
161 ```
162 */
163 readonly parseBooleans?: boolean;
164
165 /**
166 Parse the fragment identifier from the URL and add it to result object.
167
168 @default false
169
170 @example
171 ```
172 import queryString from 'query-string';
173
174 queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true});
175 //=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'}
176 ```
177 */
178 readonly parseFragmentIdentifier?: boolean;
179
180 /**
181 Specify a pre-defined schema to be used when parsing values. The types specified will take precedence over options such as: `parseNumber`, `parseBooleans`, and `arrayFormat`.
182
183 Use this feature to override the type of a value. This can be useful when the type is ambiguous such as a phone number (see example 1 and 2).
184
185 It is possible to provide a custom function as the parameter type. The parameter's value will equal the function's return value (see example 4).
186
187 NOTE: Array types (`string[]` and `number[]`) will have no effect if `arrayFormat` is set to `none` (see example 5).
188
189 @default {}
190
191 @example
192 Parse `phoneNumber` as a string, overriding the `parseNumber` option:
193 ```
194 import queryString from 'query-string';
195
196 queryString.parse('?phoneNumber=%2B380951234567&id=1', {
197 parseNumbers: true,
198 types: {
199 phoneNumber: 'string',
200 }
201 });
202 //=> {phoneNumber: '+380951234567', id: 1}
203 ```
204
205 @example
206 Parse `items` as an array of strings, overriding the `parseNumber` option:
207 ```
208 import queryString from 'query-string';
209
210 queryString.parse('?age=20&items=1%2C2%2C3', {
211 parseNumber: true,
212 types: {
213 items: 'string[]',
214 }
215 });
216 //=> {age: 20, items: ['1', '2', '3']}
217 ```
218
219 @example
220 Parse `age` as a number, even when `parseNumber` is false:
221 ```
222 import queryString from 'query-string';
223
224 queryString.parse('?age=20&id=01234&zipcode=90210', {
225 types: {
226 age: 'number',
227 }
228 });
229 //=> {age: 20, id: '01234', zipcode: '90210 }
230 ```
231
232 @example
233 Parse `age` using a custom value parser:
234 ```
235 import queryString from 'query-string';
236
237 queryString.parse('?age=20&id=01234&zipcode=90210', {
238 types: {
239 age: (value) => value * 2,
240 }
241 });
242 //=> {age: 40, id: '01234', zipcode: '90210 }
243 ```
244
245 @example
246 Array types will have no effect when `arrayFormat` is set to `none`
247 ```
248 queryString.parse('ids=001%2C002%2C003&foods=apple%2Corange%2Cmango', {
249 arrayFormat: 'none',
250 types: {
251 ids: 'number[]',
252 foods: 'string[]',
253 },
254 }
255 //=> {ids:'001,002,003', foods:'apple,orange,mango'}
256 ```
257
258 @example
259 Parse a query utilizing all types:
260 ```
261 import queryString from 'query-string';
262
263 queryString.parse('?ids=001%2C002%2C003&items=1%2C2%2C3&price=22%2E00&numbers=1%2C2%2C3&double=5&number=20', {
264 arrayFormat: 'comma',
265 types: {
266 ids: 'string',
267 items: 'string[]',
268 price: 'string',
269 numbers: 'number[]',
270 double: (value) => value * 2,
271 number: 'number',
272 },
273 });
274 //=> {ids: '001,002,003', items: ['1', '2', '3'], price: '22.00', numbers: [1, 2, 3], double: 10, number: 20}
275 ```
276 */
277 readonly types?: Record<
278 string,
279 'number' | 'string' | 'string[]' | 'number[]' | ((value: string) => unknown)
280 >;
281};
282
283// eslint-disable-next-line @typescript-eslint/ban-types
284export type ParsedQuery<T = string> = Record<string, T | null | Array<T | null>>;
285
286/**
287Parse a query string into an object. Leading `?` or `#` are ignored, so you can pass `location.search` or `location.hash` directly.
288
289The returned object is created with [`Object.create(null)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) and thus does not have a `prototype`.
290
291@param query - The query string to parse.
292*/
293export function parse(query: string, options: {parseBooleans: true; parseNumbers: true} & ParseOptions): ParsedQuery<string | boolean | number>;
294export function parse(query: string, options: {parseBooleans: true} & ParseOptions): ParsedQuery<string | boolean>;
295export function parse(query: string, options: {parseNumbers: true} & ParseOptions): ParsedQuery<string | number>;
296export function parse(query: string, options?: ParseOptions): ParsedQuery;
297
298export type ParsedUrl = {
299 readonly url: string;
300 readonly query: ParsedQuery;
301
302 /**
303 The fragment identifier of the URL.
304
305 Present when the `parseFragmentIdentifier` option is `true`.
306 */
307 readonly fragmentIdentifier?: string;
308};
309
310/**
311Extract the URL and the query string as an object.
312
313If the `parseFragmentIdentifier` option is `true`, the object will also contain a `fragmentIdentifier` property.
314
315@param url - The URL to parse.
316
317@example
318```
319import queryString from 'query-string';
320
321queryString.parseUrl('https://foo.bar?foo=bar');
322//=> {url: 'https://foo.bar', query: {foo: 'bar'}}
323
324queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true});
325//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'}
326```
327*/
328export function parseUrl(url: string, options?: ParseOptions): ParsedUrl;
329
330export type StringifyOptions = {
331 /**
332 Strictly encode URI components. It uses [`encodeURIComponent`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) if set to `false`. You probably [don't care](https://github.com/sindresorhus/query-string/issues/42) about this option.
333
334 @default true
335 */
336 readonly strict?: boolean;
337
338 /**
339 [URL encode](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) the keys and values.
340
341 @default true
342 */
343 readonly encode?: boolean;
344
345 /**
346 @default 'none'
347
348 - `bracket`: Serialize arrays using bracket representation:
349
350 ```
351 import queryString from 'query-string';
352
353 queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket'});
354 //=> 'foo[]=1&foo[]=2&foo[]=3'
355 ```
356
357 - `index`: Serialize arrays using index representation:
358
359 ```
360 import queryString from 'query-string';
361
362 queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'index'});
363 //=> 'foo[0]=1&foo[1]=2&foo[2]=3'
364 ```
365
366 - `comma`: Serialize arrays by separating elements with comma:
367
368 ```
369 import queryString from 'query-string';
370
371 queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'comma'});
372 //=> 'foo=1,2,3'
373
374 queryString.stringify({foo: [1, null, '']}, {arrayFormat: 'comma'});
375 //=> 'foo=1,,'
376 // Note that typing information for null values is lost
377 // and `.parse('foo=1,,')` would return `{foo: [1, '', '']}`.
378 ```
379
380 - `separator`: Serialize arrays by separating elements with character:
381
382 ```
383 import queryString from 'query-string';
384
385 queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'separator', arrayFormatSeparator: '|'});
386 //=> 'foo=1|2|3'
387 ```
388
389 - `bracket-separator`: Serialize arrays by explicitly post-fixing array names with brackets and separating elements with a custom character:
390
391 ```
392 import queryString from 'query-string';
393
394 queryString.stringify({foo: []}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
395 //=> 'foo[]'
396
397 queryString.stringify({foo: ['']}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
398 //=> 'foo[]='
399
400 queryString.stringify({foo: [1]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
401 //=> 'foo[]=1'
402
403 queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
404 //=> 'foo[]=1|2|3'
405
406 queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
407 //=> 'foo[]=1||3|||6'
408
409 queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|', skipNull: true});
410 //=> 'foo[]=1||3|6'
411
412 queryString.stringify({foo: [1, 2, 3], bar: 'fluffy', baz: [4]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
413 //=> 'foo[]=1|2|3&bar=fluffy&baz[]=4'
414 ```
415
416 - `colon-list-separator`: Serialize arrays with parameter names that are explicitly marked with `:list`:
417
418 ```js
419 import queryString from 'query-string';
420
421 queryString.stringify({foo: ['one', 'two']}, {arrayFormat: 'colon-list-separator'});
422 //=> 'foo:list=one&foo:list=two'
423 ```
424
425 - `none`: Serialize arrays by using duplicate keys:
426
427 ```
428 import queryString from 'query-string';
429
430 queryString.stringify({foo: [1, 2, 3]});
431 //=> 'foo=1&foo=2&foo=3'
432 ```
433 */
434 readonly arrayFormat?: 'bracket' | 'index' | 'comma' | 'separator' | 'bracket-separator' | 'colon-list-separator' | 'none';
435
436 /**
437 The character used to separate array elements when using `{arrayFormat: 'separator'}`.
438
439 @default ,
440 */
441 readonly arrayFormatSeparator?: string;
442
443 /**
444 Supports both `Function` as a custom sorting function or `false` to disable sorting.
445
446 If omitted, keys are sorted using `Array#sort`, which means, converting them to strings and comparing strings in Unicode code point order.
447
448 @default true
449
450 @example
451 ```
452 import queryString from 'query-string';
453
454 const order = ['c', 'a', 'b'];
455
456 queryString.stringify({a: 1, b: 2, c: 3}, {
457 sort: (itemLeft, itemRight) => order.indexOf(itemLeft) - order.indexOf(itemRight)
458 });
459 //=> 'c=3&a=1&b=2'
460 ```
461
462 @example
463 ```
464 import queryString from 'query-string';
465
466 queryString.stringify({b: 1, c: 2, a: 3}, {sort: false});
467 //=> 'b=1&c=2&a=3'
468 ```
469 */
470 readonly sort?: ((itemLeft: string, itemRight: string) => number) | false;
471
472 /**
473 Skip keys with `null` as the value.
474
475 Note that keys with `undefined` as the value are always skipped.
476
477 @default false
478
479 @example
480 ```
481 import queryString from 'query-string';
482
483 queryString.stringify({a: 1, b: undefined, c: null, d: 4}, {
484 skipNull: true
485 });
486 //=> 'a=1&d=4'
487
488 queryString.stringify({a: undefined, b: null}, {
489 skipNull: true
490 });
491 //=> ''
492 ```
493 */
494 readonly skipNull?: boolean;
495
496 /**
497 Skip keys with an empty string as the value.
498
499 @default false
500
501 @example
502 ```
503 import queryString from 'query-string';
504
505 queryString.stringify({a: 1, b: '', c: '', d: 4}, {
506 skipEmptyString: true
507 });
508 //=> 'a=1&d=4'
509 ```
510
511 @example
512 ```
513 import queryString from 'query-string';
514
515 queryString.stringify({a: '', b: ''}, {
516 skipEmptyString: true
517 });
518 //=> ''
519 ```
520 */
521 readonly skipEmptyString?: boolean;
522};
523
524export type Stringifiable = string | boolean | number | bigint | null | undefined; // eslint-disable-line @typescript-eslint/ban-types
525
526export type StringifiableRecord = Record<
527string,
528Stringifiable | readonly Stringifiable[]
529>;
530
531/**
532Stringify an object into a query string and sort the keys.
533*/
534export function stringify(
535 // TODO: Use the below instead when the following TS issues are fixed:
536 // - https://github.com/microsoft/TypeScript/issues/15300
537 // - https://github.com/microsoft/TypeScript/issues/42021
538 // Context: https://github.com/sindresorhus/query-string/issues/298
539 // object: StringifiableRecord,
540 object: Record<string, any>,
541 options?: StringifyOptions
542): string;
543
544/**
545Extract a query string from a URL that can be passed into `.parse()`.
546
547Note: This behaviour can be changed with the `skipNull` option.
548*/
549export function extract(url: string): string;
550
551export type UrlObject = {
552 readonly url: string;
553
554 /**
555 Overrides queries in the `url` property.
556 */
557 readonly query?: StringifiableRecord;
558
559 /**
560 Overrides the fragment identifier in the `url` property.
561 */
562 readonly fragmentIdentifier?: string;
563};
564
565/**
566Stringify an object into a URL with a query string and sorting the keys. The inverse of [`.parseUrl()`](https://github.com/sindresorhus/query-string#parseurlstring-options)
567
568Query items in the `query` property overrides queries in the `url` property.
569
570The `fragmentIdentifier` property overrides the fragment identifier in the `url` property.
571
572@example
573```
574queryString.stringifyUrl({url: 'https://foo.bar', query: {foo: 'bar'}});
575//=> 'https://foo.bar?foo=bar'
576
577queryString.stringifyUrl({url: 'https://foo.bar?foo=baz', query: {foo: 'bar'}});
578//=> 'https://foo.bar?foo=bar'
579
580queryString.stringifyUrl({
581 url: 'https://foo.bar',
582 query: {
583 top: 'foo'
584 },
585 fragmentIdentifier: 'bar'
586});
587//=> 'https://foo.bar?top=foo#bar'
588```
589*/
590export function stringifyUrl(
591 object: UrlObject,
592 options?: StringifyOptions
593): string;
594
595/**
596Pick query parameters from a URL.
597
598@param url - The URL containing the query parameters to pick.
599@param keys - The names of the query parameters to keep. All other query parameters will be removed from the URL.
600@param filter - A filter predicate that will be provided the name of each query parameter and its value. The `parseNumbers` and `parseBooleans` options also affect `value`.
601
602@returns The URL with the picked query parameters.
603
604@example
605```
606queryString.pick('https://foo.bar?foo=1&bar=2#hello', ['foo']);
607//=> 'https://foo.bar?foo=1#hello'
608
609queryString.pick('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true});
610//=> 'https://foo.bar?bar=2#hello'
611```
612*/
613export function pick(
614 url: string,
615 keys: readonly string[],
616 options?: ParseOptions & StringifyOptions
617): string;
618export function pick(
619 url: string,
620 filter: (key: string, value: string | boolean | number) => boolean,
621 options?: {parseBooleans: true; parseNumbers: true} & ParseOptions & StringifyOptions
622): string;
623export function pick(
624 url: string,
625 filter: (key: string, value: string | boolean) => boolean,
626 options?: {parseBooleans: true} & ParseOptions & StringifyOptions
627): string;
628export function pick(
629 url: string,
630 filter: (key: string, value: string | number) => boolean,
631 options?: {parseNumbers: true} & ParseOptions & StringifyOptions
632): string;
633
634/**
635Exclude query parameters from a URL. Like `.pick()` but reversed.
636
637@param url - The URL containing the query parameters to exclude.
638@param keys - The names of the query parameters to remove. All other query parameters will remain in the URL.
639@param filter - A filter predicate that will be provided the name of each query parameter and its value. The `parseNumbers` and `parseBooleans` options also affect `value`.
640
641@returns The URL without the excluded the query parameters.
642
643@example
644```
645queryString.exclude('https://foo.bar?foo=1&bar=2#hello', ['foo']);
646//=> 'https://foo.bar?bar=2#hello'
647
648queryString.exclude('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true});
649//=> 'https://foo.bar?foo=1#hello'
650```
651*/
652export function exclude(
653 url: string,
654 keys: readonly string[],
655 options?: ParseOptions & StringifyOptions
656): string;
657export function exclude(
658 url: string,
659 filter: (key: string, value: string | boolean | number) => boolean,
660 options?: {parseBooleans: true; parseNumbers: true} & ParseOptions & StringifyOptions
661): string;
662export function exclude(
663 url: string,
664 filter: (key: string, value: string | boolean) => boolean,
665 options?: {parseBooleans: true} & ParseOptions & StringifyOptions
666): string;
667export function exclude(
668 url: string,
669 filter: (key: string, value: string | number) => boolean,
670 options?: {parseNumbers: true} & ParseOptions & StringifyOptions
671): string;
672
\No newline at end of file