### Install query-string using npm Source: https://github.com/sindresorhus/query-string/blob/main/readme.md This command installs the query-string package using npm. Ensure you have Node.js and npm installed. Avoid installing the deprecated 'querystring' package. ```sh npm install query-string ``` -------------------------------- ### Stringify with Strict Encoding Option Source: https://github.com/sindresorhus/query-string/blob/main/readme.md This example shows how to use the `strict` option within the `stringify` method. When `strict` is set to `true` (the default), it uses `encodeURIComponent` for encoding. Setting it to `false` can disable this strict encoding, though it's generally not recommended. ```javascript import queryString from 'query-string'; queryString.stringify({ key: 'value' }, { strict: true }); //=> "key=value" queryString.stringify({ key: 'value' }, { strict: false }); //=> "key=value" ``` -------------------------------- ### Parse Query String with Array Format 'none' (Default) in JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Parses arrays by using duplicate keys, which is the default behavior when `arrayFormat` is set to `'none'`. For example, `foo=1&foo=2` results in `{foo: ['1', '2']}`. ```js import queryString from 'query-string'; queryString.parse('foo=1&foo=2&foo=3'); //=> {foo: ['1', '2', '3']} ``` -------------------------------- ### Parse Query String with Array Format 'separator' in JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Parses query strings where array elements are separated by a custom character, specified by `arrayFormatSeparator`. For example, using '|' as a separator: `foo=1|2|3`. ```js import queryString from 'query-string'; queryString.parse('foo=1|2|3', {arrayFormat: 'separator', arrayFormatSeparator: '|'}); //=> {foo: ['1', '2', '3']} ``` -------------------------------- ### Basic Usage: Parse and Stringify Query Strings in JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Demonstrates the core functionality of parsing a query string from `location.search` or `location.hash` into an object, modifying the object, and then stringifying it back into a query string for `location.search`. This uses the default options. ```js import queryString from 'query-string'; console.log(location.search); //=> '?foo=bar' const parsed = queryString.parse(location.search); console.log(parsed); //=> {foo: 'bar'} console.log(location.hash); //=> '#token=bada55cafe' const parsedHash = queryString.parse(location.hash); console.log(parsedHash); //=> {token: 'bada55cafe'} parsed.foo = 'unicorn'; parsed.ilike = 'pizza'; const stringified = queryString.stringify(parsed); //=> 'foo=unicorn&ilike=pizza' location.search = stringified; // note that `location.search` automatically prepends a question mark console.log(location.search); //=> '?foo=unicorn&ilike=pizza' ``` -------------------------------- ### Handle Multiple Keys and Arrays - JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Illustrates the module's capability to parse and stringify query parameters that have multiple values associated with the same key. When parsing, it returns an array for such keys. When stringifying, it correctly generates multiple key-value pairs for array elements. ```javascript import queryString from 'query-string'; queryString.parse('likes=cake&name=bob&likes=icecream'); //=> {likes: ['cake', 'icecream'], name: 'bob'} queryString.stringify({color: ['taupe', 'chartreuse'], id: '515'}); //=> 'color=taupe&color=chartreuse&id=515' ``` -------------------------------- ### Stringify Falsy Values - JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Explains how `queryString.stringify` handles different falsy values. `false` is stringified as 'key=false', `null` results in just the key (no value), and `undefined` omits the key entirely from the output string. ```javascript import queryString from 'query-string'; queryString.stringify({foo: false}); //=> 'foo=false' queryString.stringify({foo: null}); //=> 'foo' queryString.stringify({foo: undefined}); //=> '' ``` -------------------------------- ### Build URLs from Objects using query-string Source: https://context7.com/sindresorhus/query-string/llms.txt Constructs URLs by serializing JavaScript objects into query strings. Supports various options for array formatting, encoding, and fragment identifiers. Useful for creating API endpoints or navigation links dynamically. It can also handle browser navigation by updating the URL. ```javascript import queryString from 'query-string'; // Basic URL construction const url = queryString.stringifyUrl({ url: 'https://example.com', query: {foo: 'bar', page: 1} }); //=> 'https://example.com?foo=bar&page=1' // Override existing query parameters const override = queryString.stringifyUrl({ url: 'https://example.com?foo=old&keep=this', query: {foo: 'new', add: 'param'} }); //=> 'https://example.com?add=param&foo=new&keep=this' // Add fragment identifier const withFragment = queryString.stringifyUrl({ url: 'https://example.com', query: {section: 'docs'}, fragmentIdentifier: 'api-reference' }); //=> 'https://example.com?section=docs#api-reference' // Build API endpoint with array parameters const apiUrl = queryString.stringifyUrl({ url: 'https://api.example.com/items', query: { ids: [101, 102, 103], status: 'active', limit: 50 } }, { arrayFormat: 'comma' }); //=> 'https://api.example.com/items?ids=101,102,103&limit=50&status=active' // Build URL with custom encoding const customEncoded = queryString.stringifyUrl({ url: 'https://example.com/search', query: { q: 'hello world', tags: ['javascript', 'node.js'] } }, { arrayFormat: 'bracket', encode: true, strict: true }); //=> 'https://example.com/search?q=hello%20world&tags[]=javascript&tags[]=node.js' // Browser navigation example if (typeof window !== 'undefined') { const newUrl = queryString.stringifyUrl({ url: window.location.origin + window.location.pathname, query: { page: 2, filter: 'recent', sort: 'desc' } }); window.history.pushState({}, '', newUrl); } ``` -------------------------------- ### Pick Query Parameters by Filter Function - query-string Source: https://github.com/sindresorhus/query-string/blob/main/readme.md This overload of '.pick(url, filter, options?)' allows for more dynamic selection of query parameters using a filter function. The function receives the parameter name and value, and returns 'true' to include the parameter. Options like 'parseNumbers' can affect the value passed to the filter. ```javascript import queryString from 'query-string'; queryString.pick('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true}); //=> 'https://foo.bar?bar=2#hello' ``` -------------------------------- ### Stringify with skipNull: true Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Skips keys where the value is `null`. Keys with `undefined` values are always skipped. Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({a: 1, b: undefined, c: null, d: 4}, { skipNull: true }); //=> 'a=1&d=4' ``` ```javascript import queryString from 'query-string'; queryString.stringify({a: undefined, b: null}, { skipNull: true }); //=> '' ``` -------------------------------- ### Parse Query String with Default Options in JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Parses a query string into an object. Leading '?' or '#' characters are ignored. The resulting object is created with `Object.create(null)`, meaning it has no prototype. ```js import queryString from 'query-string'; queryString.parse('?foo=bar'); //=> {foo: 'bar'} queryString.parse('#token=secret&name=jhon'); //=> {token: 'secret', name: 'jhon'} ``` -------------------------------- ### Stringify with skipEmptyString: true Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Skips keys where the value is an empty string. Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({a: 1, b: '', c: '', d: 4}, { skipEmptyString: true }); //=> 'a=1&d=4' ``` ```javascript import queryString from 'query-string'; queryString.stringify({a: '', b: ''}, { skipEmptyString: true }); //=> '' ``` -------------------------------- ### Parse Complete URLs with Query Strings using query-string Source: https://context7.com/sindresorhus/query-string/llms.txt This section explains how to use `queryString.parseUrl` to parse a full URL into its constituent parts: the base URL, the query parameters, and optionally the fragment identifier. It details options for parsing array formats, enabling type conversion for numbers and booleans, and parsing fragment identifiers. This function is particularly useful in browser environments for analyzing `window.location.href`. ```javascript import queryString from 'query-string'; // Parse URL into components const parsed = queryString.parseUrl('https://example.com/path?foo=bar&id=5'); //=> { // url: 'https://example.com/path', // query: {foo: 'bar', id: '5'} // } // Parse with fragment identifier const withHash = queryString.parseUrl('https://example.com?foo=bar#section', { parseFragmentIdentifier: true }); //=> { // url: 'https://example.com', // query: {foo: 'bar'}, // fragmentIdentifier: 'section' // } // Parse with type conversion const withTypes = queryString.parseUrl('https://api.example.com/users?age=25&active=true', { parseNumbers: true, parseBooleans: true }); //=> { // url: 'https://api.example.com/users', // query: {age: 25, active: true} // } // Parse arrays in URL const withArrays = queryString.parseUrl('https://shop.com/search?colors=red,blue,green', { arrayFormat: 'comma' }); //=> { // url: 'https://shop.com/search', // query: {colors: ['red', 'blue', 'green']} // } // In browser context if (typeof window !== 'undefined') { const currentPage = queryString.parseUrl(window.location.href, { parseFragmentIdentifier: true, parseNumbers: true, parseBooleans: true }); console.log(currentPage.query); // Access all URL params as typed values } ``` -------------------------------- ### Pick Query Parameters by Keys - query-string Source: https://github.com/sindresorhus/query-string/blob/main/readme.md The '.pick(url, keys, options?)' function extracts specific query parameters from a URL based on an array of keys. It returns a new URL string containing only the selected parameters and the original fragment identifier. ```javascript import queryString from 'query-string'; queryString.pick('https://foo.bar?foo=1&bar=2#hello', ['foo']); //=> 'https://foo.bar?foo=1#hello' ``` -------------------------------- ### Stringify with arrayFormat: 'colon-list-separator' Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Serializes arrays by appending `:list` to parameter names (e.g., `foo:list=one&foo:list=two`). Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({foo: ['one', 'two']}, {arrayFormat: 'colon-list-separator'}); //=> 'foo:list=one&foo:list=two' ``` -------------------------------- ### Stringify Objects into Query Strings with query-string Source: https://context7.com/sindresorhus/query-string/llms.txt This section demonstrates how to use the `queryString.stringify` method to convert JavaScript objects into URL query strings. It covers basic stringification, various array formats (duplicate keys, bracket, index, comma, custom separator), skipping null and empty string values, custom sorting, disabling sorting, and using a replacer function for complex types. Undefined values are always skipped. Options like `skipNull`, `skipEmptyString`, `arrayFormat`, `sort`, and `replacer` can be passed as the second argument. ```javascript import queryString from 'query-string'; // Basic stringification - keys are sorted by default const basic = queryString.stringify({foo: 'bar', baz: 'qux'}); //=> 'baz=qux&foo=bar' // Stringify arrays (default: duplicate keys) const arrays = queryString.stringify({colors: ['red', 'green', 'blue']}); //=> 'colors=red&colors=green&colors=blue' // Stringify arrays with bracket format const bracket = queryString.stringify({ids: [1, 2, 3]}, { arrayFormat: 'bracket' }); //=> 'ids[]=1&ids[]=2&ids[]=3' // Stringify arrays with index format const index = queryString.stringify({items: ['a', 'b', 'c']}, { arrayFormat: 'index' }); //=> 'items[0]=a&items[1]=b&items[2]=c' // Stringify arrays with comma separator const comma = queryString.stringify({tags: ['javascript', 'node', 'web']}, { arrayFormat: 'comma' }); //=> 'tags=javascript,node,web' // Stringify with custom separator const custom = queryString.stringify({ports: [8080, 3000, 5000]}, { arrayFormat: 'separator', arrayFormatSeparator: '|' }); //=> 'ports=8080|3000|5000' // Skip null values const skipNull = queryString.stringify({a: 1, b: null, c: undefined, d: 4}, { skipNull: true }); //=> 'a=1&d=4' (undefined is always skipped) // Skip empty strings const skipEmpty = queryString.stringify({name: 'John', title: '', role: 'admin'}, { skipEmptyString: true }); //=> 'name=John&role=admin' // Custom sorting function const customSort = queryString.stringify({z: 3, a: 1, m: 2}, { sort: (a, b) => a.localeCompare(b) // Alphabetical order }); //=> 'a=1&m=2&z=3' // Disable sorting to use object key order const noSort = queryString.stringify({z: 3, a: 1, m: 2}, {sort: false}); //=> 'z=3&a=1&m=2' // Custom replacer for complex types const withDate = queryString.stringify({ created: new Date('2024-01-15T10:30:00Z'), name: 'Project Alpha', internal: true }, { replacer: (key, value) => { if (value instanceof Date) { return value.toISOString(); } if (key === 'internal') { return undefined; // Omit internal fields } return value; } }); //=> 'created=2024-01-15T10%3A30%3A00.000Z&name=Project+Alpha' // Handle falsy values queryString.stringify({active: false}); //=> 'active=false' queryString.stringify({key: null}); //=> 'key' queryString.stringify({key: undefined}); //=> '' ``` -------------------------------- ### Stringify with arrayFormat: 'none' Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Serializes arrays using duplicate keys (e.g., `foo=1&foo=2`). This is the default behavior if `arrayFormat` is not specified. Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({foo: [1, 2, 3]}); //=> 'foo=1&foo=2&foo=3' ``` -------------------------------- ### Stringify with arrayFormat: 'index' Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Serializes arrays using index notation (e.g., `foo[0]=1&foo[1]=2`). Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'index'}); //=> 'foo[0]=1&foo[1]=2&foo[2]=3' ``` -------------------------------- ### Stringify with arrayFormat: 'bracket' Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Serializes arrays using bracket notation (e.g., `foo[]=1&foo[]=2`). Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket'}); //=> 'foo[]=1&foo[]=2&foo[]=3' ``` -------------------------------- ### Stringify Object with JSON Nested Value - JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Demonstrates how to handle nested objects by stringifying them to JSON before passing to `queryString.stringify`. This is the recommended approach as the module does not natively support nesting. It takes an object as input and outputs a query string. ```javascript import queryString from 'query-string'; queryString.stringify({ foo: 'bar', nested: JSON.stringify({ unicorn: 'cake' }) }); //=> 'foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D' ``` -------------------------------- ### Stringify URL with Query String - query-string Source: https://github.com/sindresorhus/query-string/blob/main/readme.md The '.stringifyUrl(object, options?)' function constructs a URL string from a given object, including a query string. It can merge or override query parameters present in the 'url' property with those in the 'query' property, and similarly handle fragment identifiers. ```javascript queryString.stringifyUrl({url: 'https://foo.bar', query: {foo: 'bar'}}); //=> 'https://foo.bar?foo=bar' queryString.stringifyUrl({url: 'https://foo.bar?foo=baz', query: {foo: 'bar'}}); //=> 'https://foo.bar?foo=bar' queryString.stringifyUrl({ url: 'https://foo.bar', query: { top: 'foo' }, fragmentIdentifier: 'bar' }); //=> 'https://foo.bar?top=foo#bar' ``` -------------------------------- ### Stringify with Encode Option Source: https://github.com/sindresorhus/query-string/blob/main/readme.md This code illustrates the use of the `encode` option in the `stringify` method. When `encode` is `true` (the default), both keys and values are URL-encoded. Setting it to `false` prevents any encoding, which might be necessary in specific scenarios but requires careful handling. ```javascript import queryString from 'query-string'; queryString.stringify({ key: 'value' }, { encode: true }); //=> "key=value" queryString.stringify({ key: 'value' }, { encode: false }); //=> "key=value" ``` -------------------------------- ### Stringify with Custom Replacer - query-string Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Demonstrates using the 'replacer' function to transform values before stringification, such as converting Dates to ISO strings or omitting keys. The replacer receives key-value pairs and should return the transformed value; returning 'undefined' omits the pair. ```javascript import queryString from 'query-string'; queryString.stringify({ date: new Date('2024-01-15T10:30:00Z'), name: 'John' }, { replacer: (key, value) => { if (value instanceof Date) { return value.toISOString(); } return value; } }); //=> 'date=2024-01-15T10%3A30%3A00.000Z&name=John' ``` ```javascript import queryString from 'query-string'; queryString.stringify({ a: 1, b: null, c: 3 }, { replacer: (key, value) => value === null ? undefined : value }); //=> 'a=1&c=3' ``` -------------------------------- ### Parse URL and Query String - query-string Source: https://github.com/sindresorhus/query-string/blob/main/readme.md The '.parseUrl(string, options?)' function parses a URL, separating it into its constituent parts: the base URL and the query string. It returns an object containing these components, and optionally the fragment identifier if 'parseFragmentIdentifier' is enabled. ```javascript import queryString from 'query-string'; queryString.parseUrl('https://foo.bar?foo=bar'); //=> {url: 'https://foo.bar', query: {foo: 'bar'}} queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true}); //=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'} ``` ```javascript import queryString from 'query-string'; queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true}); //=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'} ``` -------------------------------- ### Query String Parsing API Source: https://github.com/sindresorhus/query-string/blob/main/readme.md The `.parse()` method in the query-string library takes a URL query string and converts it into a JavaScript object. It can handle leading '?' or '#' characters and offers options for decoding, array formatting, number parsing, and key sorting. ```APIDOC ## .parse(string, options?) ### Description Parse a query string into an object. Leading `?` or `#` are ignored, so you can pass `location.search` or `location.hash` directly. The returned object is created with `Object.create(null)` and thus does not have a `prototype`. ### Method `queryString.parse(string, options?) ### Endpoint N/A (JavaScript function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript queryString.parse('?foo=bar'); //=> {foo: 'bar'} queryString.parse('#token=secret&name=jhon'); //=> {token: 'secret', name: 'jhon'} ``` ### Response #### Success Response (Object) - **keys** (string) - Parsed query string parameters. #### Response Example ```json { "foo": "bar", "token": "secret", "name": "jhon" } ``` ### Options #### `decode` - **Type**: `boolean` - **Default**: `true` - **Description**: Decode the keys and values. URL components are decoded with `decode-uri-component`. #### `arrayFormat` - **Type**: `string` - **Default**: `'none'` - **Description**: Specifies how to parse arrays. Supported values include `'bracket'`, `'index'`, `'comma'`, `'separator'`, `'bracket-separator'`, `'colon-list-separator'`, and `'none'`. - `'bracket'`: Parses arrays like `foo[]=1&foo[]=2` into `{foo: ['1', '2']}`. - `'index'`: Parses arrays like `foo[0]=1&foo[1]=2` into `{foo: ['1', '2']}`. - `'comma'`: Parses arrays like `foo=1,2,3` into `{foo: ['1', '2', '3']}`. - `'separator'`: Parses arrays with elements separated by `arrayFormatSeparator`. Example: `foo=1|2|3` with `arrayFormatSeparator: '|'` parses to `{foo: ['1', '2', '3']}`. - `'bracket-separator'`: Parses explicitly bracketed arrays with a separator. Example: `foo[]=1|2|3` with `arrayFormatSeparator: '|'` parses to `{foo: ['1', '2', '3']}`. - `'colon-list-separator'`: Parses arrays with parameter names like `foo:list=one&foo:list=two` into `{foo: ['one', 'two']}`. - `'none'`: Parses arrays using duplicate keys. Example: `foo=1&foo=2` parses to `{foo: ['1', '2']}`. #### `arrayFormatSeparator` - **Type**: `string` - **Default**: `','` - **Description**: The character used to separate array elements when `arrayFormat` is set to `'separator'` or `'bracket-separator'`. #### `sort` - **Type**: `Function | boolean` - **Default**: `true` - **Description**: Supports a `Function` for custom sorting of keys or `false` to disable sorting. #### `parseNumbers` - **Type**: `boolean` - **Default**: `false` - **Description**: If `true`, values that are numbers will be parsed as numbers instead of strings. ```javascript queryString.parse('foo=1', {parseNumbers: true}); //=> {foo: 1} ``` ``` -------------------------------- ### Stringify with arrayFormat: 'comma' Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Serializes arrays by joining elements with a comma (e.g., `foo=1,2,3`). Note that `null` values are lost during serialization and parsed as empty strings. Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'comma'}); //=> 'foo=1,2,3' queryString.stringify({foo: [1, null, '']}, {arrayFormat: 'comma'}); //=> 'foo=1,,' // Note that typing information for null values is lost // and `.parse('foo=1,,')` would return `{foo: [1, '', '']}`. ``` -------------------------------- ### Parse Query Strings to Objects with query-string (JavaScript) Source: https://context7.com/sindresorhus/query-string/llms.txt Parses URL query strings into JavaScript objects. It supports basic parsing, handling numbers and booleans, multiple array formats (bracket, comma, separator), custom type parsing via a schema, custom transformation functions, and options for sorting or preserving order. Leading '?' or '#' are ignored. ```javascript import queryString from 'query-string'; // Basic parsing - leading ? or # are ignored const parsed = queryString.parse('?foo=bar&name=john'); //=> {foo: 'bar', name: 'john'} // Parse location.search directly in browser const params = queryString.parse(location.search); //=> {foo: 'bar'} (if URL is https://example.com?foo=bar) // Parse with numbers and booleans const typed = queryString.parse('?age=25&active=true&score=98.5', { parseNumbers: true, parseBooleans: true }); //=> {age: 25, active: true, score: 98.5} // Parse arrays with bracket format const arrays = queryString.parse('foo[]=1&foo[]=2&foo[]=3', { arrayFormat: 'bracket' }); //=> {foo: ['1', '2', '3']} // Parse arrays with comma separator const comma = queryString.parse('colors=red,green,blue', { arrayFormat: 'comma' }); //=> {colors: ['red', 'green', 'blue']} // Parse arrays with custom separator const custom = queryString.parse('ids=100|200|300', { arrayFormat: 'separator', arrayFormatSeparator: '|' }); //=> {ids: ['100', '200', '300']} // Custom type parsing with explicit schema const withTypes = queryString.parse('?phone=%2B1234567890&age=30&items=a,b,c', { parseNumbers: true, arrayFormat: 'comma', types: { phone: 'string', // Keep as string even if looks like number age: 'number', // Parse as number items: 'string[]', // Array of strings, not numbers } }); //=> {phone: '+1234567890', age: 30, items: ['a', 'b', 'c']} // Custom transformation function const transformed = queryString.parse('?price=100&discount=20', { types: { discount: value => Number(value) / 100 // Convert percentage to decimal } }); //=> {price: '100', discount: 0.2} // Custom sorting const sorted = queryString.parse('?z=3&a=1&m=2', { sort: (a, b) => b.localeCompare(a) // Reverse alphabetical }); //=> {z: '3', m: '2', a: '1'} // Disable sorting to preserve order const unsorted = queryString.parse('?z=3&a=1&m=2', {sort: false}); //=> {z: '3', a: '1', m: '2'} ``` -------------------------------- ### Explicitly Define Query String Types Source: https://github.com/sindresorhus/query-string/blob/main/readme.md This section shows how to use the `types` option to explicitly define the parsing behavior for specific query parameters. This allows for precise control over type conversion, overriding general parsing options. It supports predefined types like 'boolean', 'string', 'number', 'string[]', and 'number[]', as well as custom functions for transformation. ```javascript queryString.parse('?isAdmin=true&flagged=true&isOkay=0', { parseBooleans: false, types: { flagged: 'boolean', isOkay: 'boolean', }, }); //=> {isAdmin: 'true', flagged: true, isOkay: false} ``` ```javascript import queryString from 'query-string'; queryString.parse('?phoneNumber=%2B380951234567&id=1', { parseNumbers: true, types: { phoneNumber: 'string', } }); //=> {phoneNumber: '+380951234567', id: 1} ``` ```javascript import queryString from 'query-string'; queryString.parse('?age=20&id=01234&zipcode=90210', { types: { age: 'number', } }); //=> {age: 20, id: '01234', zipcode: '90210'} ``` ```javascript import queryString from 'query-string'; queryString.parse('?age=20&items=1%2C2%2C3', { parseNumbers: true, types: { items: 'string[]', } }); //=> {age: 20, items: ['1', '2', '3']} ``` ```javascript import queryString from 'query-string'; queryString.parse('?age=20&items=1%2C2%2C3', { types: { items: 'number[]', } }); //=> {age: '20', items: [1, 2, 3]} ``` ```javascript import queryString from 'query-string'; queryString.parse('?age=20&id=01234&zipcode=90210', { types: { age: value => value * 2, } }); //=> {age: 40, id: '01234', zipcode: '90210'} // With arrays, the function is applied to each element queryString.parse('?scores=10,20,30', { arrayFormat: 'comma', types: { scores: value => Number(value) * 2, } }); //=> {scores: [20, 40, 60]} ``` ```javascript queryString.parse('ids=001%2C002%2C003&foods=apple%2Corange%2Cmango', { arrayFormat: 'none', types: { ids: 'number[]', foods: 'string[]', }, } //=> {ids:'001,002,003', foods:'apple,orange,mango'} ``` -------------------------------- ### Extract Query Strings from URLs using query-string Source: https://context7.com/sindresorhus/query-string/llms.txt Extracts the raw query string part from a given URL. It correctly handles URLs with or without query parameters, relative URLs, and URLs containing hash fragments. The extracted string can then be parsed further. ```javascript import queryString from 'query-string'; // Extract query string only const query = queryString.extract('https://example.com?foo=bar&id=5'); //=> 'foo=bar&id=5' // Works with hash fragments const withHash = queryString.extract('https://example.com?foo=bar#section'); //=> 'foo=bar' // Extract from relative URLs const relative = queryString.extract('/api/users?limit=10&offset=20'); //=> 'limit=10&offset=20' // Returns empty string if no query const noQuery = queryString.extract('https://example.com/path'); //=> '' // Combine with parse for full workflow const url = 'https://example.com/search?q=javascript&sort=stars'; const queryStr = queryString.extract(url); const params = queryString.parse(queryStr, {parseNumbers: true}); //=> {q: 'javascript', sort: 'stars'} ``` -------------------------------- ### Query String Stringify API Source: https://github.com/sindresorhus/query-string/blob/main/readme.md The `.stringify()` method converts a JavaScript object into a URL query string. It supports various options for formatting arrays and sorting keys. ```APIDOC ## .stringify(object, options?) ### Description Convert an object into a query string. ### Method `queryString.stringify(object, options?) ### Endpoint N/A (JavaScript function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **object** (object) - The object to convert into a query string. ### Request Example ```javascript const parsed = {foo: 'unicorn', ilike: 'pizza'}; const stringified = queryString.stringify(parsed); //=> 'foo=unicorn&ilike=pizza' ``` ### Response #### Success Response (string) - **queryString** (string) - The generated query string. #### Response Example ```json "foo=unicorn&ilike=pizza" ``` ### Options #### `arrayFormat` - **Type**: `string` - **Default**: `'none'` - **Description**: Specifies how to stringify arrays. Supported values are `'bracket'`, `'index'`, `'comma'`, `'separator'`, `'bracket-separator'`, `'colon-list-separator'`, and `'none'`. - `'bracket'`: Stringifies arrays like `{foo: ['1', '2']}` to `foo[]=1&foo[]=2`. - `'index'`: Stringifies arrays like `{foo: ['1', '2']}` to `foo[0]=1&foo[1]=2`. - `'comma'`: Stringifies arrays like `{foo: ['1', '2']}` to `foo=1,2`. - `'separator'`: Stringifies arrays with elements separated by `arrayFormatSeparator`. Example: `{foo: ['1', '2']}` with `arrayFormatSeparator: '|'` stringifies to `foo=1|2`. - `'bracket-separator'`: Stringifies arrays with explicit brackets and a separator. Example: `{foo: ['1', '2']}` with `arrayFormatSeparator: '|'` stringifies to `foo[]=1|2`. - `'colon-list-separator'`: Stringifies arrays using the `:list` syntax. Example: `{foo: ['one', 'two']}` stringifies to `foo:list=one&foo:list=two`. - `'none'`: Stringifies arrays using duplicate keys. Example: `{foo: ['1', '2']}` stringifies to `foo=1&foo=2`. #### `arrayFormatSeparator` - **Type**: `string` - **Default**: `','` - **Description**: The character used to separate array elements when `arrayFormat` is set to `'separator'` or `'bracket-separator'`. #### `sort` - **Type**: `Function | boolean` - **Default**: `true` - **Description**: Supports a `Function` for custom sorting of keys or `false` to disable sorting. #### `encode` - **Type**: `boolean` - **Default**: `true` - **Description**: Encode the keys and values. URL components are encoded with `encode-uri-component`. #### `strictNullHandling` - **Type**: `boolean` - **Default**: `false` - **Description**: If `true`, `null` values will be encoded as `key` instead of being ignored. ```javascript queryString.stringify({foo: null}, {strictNullHandling: true}); //=> 'foo' ``` #### `skipNulls` - **Type**: `boolean` - **Default**: `false` - **Description**: If `true`, `null` values will be ignored. ```javascript queryString.stringify({foo: null}); //=> '' ``` #### `filter` - **Type**: `Function | string[] | boolean` - **Default**: `false` - **Description**: Allows filtering of parameters. Can be a function that returns `true` to include or `false` to exclude a key-value pair, an array of keys to include, or `true` to include all keys. ```javascript // Filter with a function queryString.stringify({foo: 1, bar: 2}, {filter: key => key === 'foo'}); //=> 'foo=1' // Filter with an array of keys queryString.stringify({foo: 1, bar: 2}, {filter: ['foo']}); //=> 'foo=1' ``` #### `formatters` - **Type**: `object` - **Description**: An object mapping formatter names to functions that serialize values. Useful for custom data types. ```javascript const formatters = { date: (value) => value.getTime() }; queryString.stringify({date: new Date()}, {formatters}); //=> 'date=1678886400000' (example timestamp) ``` ``` -------------------------------- ### Stringify with arrayFormat: 'bracket-separator' Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Serializes arrays with brackets and a custom separator (e.g., `foo[]=1|2|3`). Handles empty arrays and various value types. Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({foo: []}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> 'foo[]' queryString.stringify({foo: ['']}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> 'foo[]=' queryString.stringify({foo: [1]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> 'foo[]=1' queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> 'foo[]=1|2|3' queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> 'foo[]=1||3|||6' queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|', skipNull: true}); //=> 'foo[]=1||3|6' queryString.stringify({foo: [1, 2, 3], bar: 'fluffy', baz: [4]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> 'foo[]=1|2|3&bar=fluffy&baz[]=4' ``` -------------------------------- ### Pick Specific Query Parameters from URLs using query-string Source: https://context7.com/sindresorhus/query-string/llms.txt Filters URL parameters, allowing selection by specific keys or a filtering function. It preserves the original URL structure, including fragment identifiers, and supports various parsing options for values. This is useful for sanitizing or selecting relevant data from a URL. ```javascript import queryString from 'query-string'; // Pick parameters by key names const picked = queryString.pick('https://example.com?foo=1&bar=2&baz=3', ['foo', 'baz']); //=> 'https://example.com?baz=3&foo=1' // Preserves fragment identifier const withHash = queryString.pick('https://example.com?foo=1&bar=2#section', ['foo']); //=> 'https://example.com?foo=1#section' // Pick with filter function const filtered = queryString.pick( 'https://api.example.com?status=active&limit=10&offset=0&debug=true', (key, value) => value !== 'true', {parseBooleans: true} ); //=> 'https://api.example.com?limit=10&offset=0&status=active' // Pick numeric values only const numbersOnly = queryString.pick( 'https://example.com?id=123&name=john&age=25&role=admin', (key, value) => typeof value === 'number', {parseNumbers: true} ); //=> 'https://example.com?age=25&id=123' // Pick with array formatting preserved const withArrays = queryString.pick( 'https://shop.com?colors=red,blue&sizes=S,M,L&brand=Nike', ['colors', 'sizes'], {arrayFormat: 'comma'} ); //=> 'https://shop.com?colors=red,blue&sizes=S,M,L' ``` -------------------------------- ### Stringify Object to Query String Source: https://github.com/sindresorhus/query-string/blob/main/readme.md This snippet demonstrates how to convert a JavaScript object into a URL query string. It supports various value types including strings, numbers, booleans, null, undefined, and arrays. The `stringify` method also includes options for controlling URI encoding and key sorting. ```javascript import queryString from 'query-string'; queryString.stringify({ foo: 'bar', baz: [1, 2, 3] }); //=> "foo=bar&baz[]=1&baz[]=2&baz[]=3" ``` -------------------------------- ### Parse Booleans in Query String Source: https://github.com/sindresorhus/query-string/blob/main/readme.md This snippet demonstrates how to parse boolean values directly from a query string. When `parseBooleans` is enabled, string representations of booleans like 'true' and 'false' are converted to their corresponding boolean types. This is useful for handling boolean flags in URLs. ```javascript import queryString from 'query-string'; queryString.parse('foo=true', {parseBooleans: true}); //=> {foo: true} ``` -------------------------------- ### Stringify with custom sort function Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Sorts query string keys using a custom comparison function. If `sort` is `false`, sorting is disabled. By default, keys are sorted using `Array#sort()`. Requires the `query-string` library. ```javascript import queryString from 'query-string'; const order = ['c', 'a', 'b']; queryString.stringify({a: 1, b: 2, c: 3}, { sort: (a, b) => order.indexOf(a) - order.indexOf(b) }); //=> 'c=3&a=1&b=2' ``` ```javascript import queryString from 'query-string'; queryString.stringify({b: 1, c: 2, a: 3}, {sort: false}); //=> 'b=1&c=2&a=3' ``` -------------------------------- ### Stringify with arrayFormat: 'separator' Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Serializes arrays using a custom separator character (e.g., `foo=1|2|3`). The separator is defined by `arrayFormatSeparator`. Requires the `query-string` library. ```javascript import queryString from 'query-string'; queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'separator', arrayFormatSeparator: '|'}); //=> 'foo=1|2|3' ``` -------------------------------- ### Exclude Query Parameters by Filter Function - query-string Source: https://github.com/sindresorhus/query-string/blob/main/readme.md This overload of '.exclude(url, filter, options?)' enables the exclusion of query parameters based on a filter function. The function evaluates each parameter; if it returns 'true', the parameter is excluded. Options like 'parseNumbers' influence the value provided to the filter. ```javascript import queryString from 'query-string'; queryString.exclude('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true}); //=> 'https://foo.bar?foo=1#hello' ``` -------------------------------- ### Parse Query String with Array Format 'index' in JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Parses query strings where array elements are represented using indexed bracket notation (e.g., `foo[0]=1&foo[1]=2`). This allows for specific index assignment. ```js import queryString from 'query-string'; queryString.parse('foo[0]=1&foo[1]=2&foo[3]=3', {arrayFormat: 'index'}); //=> {foo: ['1', '2', '3']} ``` -------------------------------- ### Parse Query String with Array Format 'bracket-separator' in JavaScript Source: https://github.com/sindresorhus/query-string/blob/main/readme.md Parses array elements separated by a custom character, but only when the key explicitly uses bracket notation (e.g., `foo[]=1|2|3`). Handles empty elements and multiple keys. ```js import queryString from 'query-string'; queryString.parse('foo[]', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> {foo: []} queryString.parse('foo[]=', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> {foo: ['']} queryString.parse('foo[]=1', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> {foo: ['1']} queryString.parse('foo[]=1|2|3', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> {foo: ['1', '2', '3']} queryString.parse('foo[]=1||3|||6', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> {foo: ['1', '', 3, '', '', '6']} queryString.parse('foo[]=1|2|3&bar=fluffy&baz[]=4', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'}); //=> {foo: ['1', '2', '3'], bar: 'fluffy', baz:['4']} ```