query-string

repository·main·Indexed 27 days ago

https://github.com/sindresorhus/query-string

A utility for parsing and stringifying URL query strings, providing a robust alternative to native APIs. It includes methods to convert query strings or URL hashes into JavaScript objects via .parse(), and objects back into URL-encoded strings via .stringify(). Additional features include .extract(), .parseUrl(), .stringifyUrl(), and tools to filter parameters using .pick() and .exclude(). Supports various array formats, explicit type declarations, and TypeScript types such as ParseOptions and StringifyOptions.

Tokens
3.4K
Snippets
13
Records
17
Agent score
42%

What's inside query-string

  1. Install query-string via npm

    main

    Install the query-string package using npm.

    Warning: Ensure you use the hyphenated name query-string. Do not install the deprecated querystring package.

    For browser environments, this package targets the latest versions of Chrome, Firefox, and Safari. For very simple use cases, you may want to consider using the native URLSearchParams API instead.

    npm install query-string
  2. Handle nested objects in query strings

    main

    The query-string module does not support nested objects because nesting is not standardized across implementations. To include nested data, convert the object to a JSON string before passing it to stringify.

    import queryString from 'query-string';
    
    queryString.stringify({
    	foo: 'bar',
    	nested: JSON.stringify({
    		unicorn: 'cake'
    	})
    });
    //=> 'foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D'
  3. Handle multiple instances of the same key

    main

    The module supports multiple instances of the same key. When parsing, these are returned as an array. When stringifying, arrays are expanded into multiple key-value pairs.

    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'
  4. Stringify objects into query strings with query-string

    main

    Use queryString.stringify() to convert a JavaScript object into a URL-encoded query string.

    import queryString from 'query-string';
    
    const parsed = {foo: 'unicorn', ilike: 'pizza'};
    const stringified = queryString.stringify(parsed);
    //=> 'foo=unicorn&ilike=pizza'
    import queryString from 'query-string';
    
    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'
  5. Use explicit types in .parse()

    main

    Use the types option in .parse() to define specific schemas for parameters. This is useful for disambiguating types (like phone numbers) or applying custom transformations. Supported types include 'boolean', 'string', 'number', 'string[]', 'number[]', and custom Function transformations.

    import queryString from 'query-string';
    
    // Custom transformation function
    queryString.parse('?age=20&id=01234&zipcode=90210', {
    	types: {
    		age: value => value * 2,
    	}
    });
    //=> {age: 40, id: '01234', zipcode: '90210'}
    
    // Array with custom function applied to each element
    queryString.parse('?scores=10,20,30', {
    	arrayFormat: 'comma',
    	types: {
    		scores: value => Number(value) * 2,
    	},
    });
    //=> {scores: [20, 40, 60]}
  6. Parse query strings and hashes with query-string

    main

    Use queryString.parse() to convert a query string (e.g., ?foo=bar) or a URL hash (e.g., #token=bada55cafe) into a plain JavaScript object.

    import queryString from 'query-string';
    
    const parsed = queryString.parse('?foo=bar');
    //=> {foo: 'bar'}
    
    const parsedHash = queryString.parse('#token=bada55cafe');
    //=> {token: 'bada55cafe'}
    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'}
  7. Filter query parameters with .pick() and .exclude()

    main

    Modify a URL by selecting or removing specific query parameters.

    • .pick(url, keys, options?) or .pick(url, filter, options?): Returns a new URL containing only the specified keys or those that satisfy the filter predicate.
    • .exclude(url, keys, options?) or .exclude(url, filter, options?): Returns a new URL excluding the specified keys or those that satisfy the filter predicate.
    import queryString from 'query-string';
    
    // Pick specific keys
    queryString.pick('https://foo.bar?foo=1&bar=2#hello', ['foo']);
    //=> 'https://foo.bar?foo=1#hello'
    
    // Pick using a filter function
    queryString.pick('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true});
    //=> 'https://foo.bar?bar=2#hello'
    
    // Exclude specific keys
    queryString.exclude('https://foo.bar?foo=1&bar=2#hello', ['foo']);
    //=> 'https://foo.bar?bar=2#hello'
  8. Stringify URLs with .stringifyUrl()

    main

    Convert an object into a full URL string. The object must contain a url property. You can also provide a query object and a fragmentIdentifier. Items in the query object override existing queries in the url string.

    import queryString from 'query-string';
    
    queryString.stringifyUrl({url: 'https://foo.bar', 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'
  9. Stringify an object with .stringify()

    main

    Convert a JavaScript object into a query string. Keys are sorted by default. Supported value types are string, number, bigint, boolean, null, undefined, and arrays of these types.

    // Basic usage
    queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket'});
    //=> 'foo[]=1&foo[]=2&foo[]=3'
  10. Configure .parse() options

    main

    The .parse(string, options?) method accepts several options to control parsing behavior:

    • decode (boolean, default: true): Whether to decode keys and values using decode-uri-component.
    • arrayFormat (string, default: 'none'): Defines how arrays are represented in the string. Supported values:
      • 'bracket': foo[]=1&foo[]=2
      • 'index': foo[0]=1&foo[1]=2
      • 'comma': foo=1,2,3
      • 'separator': foo=1|2|3 (requires arrayFormatSeparator)
      • 'bracket-separator': foo[]=1|2|3 (requires arrayFormatSeparator)
      • 'colon-list-separator': foo:list=one&foo:list=two
      • 'none': foo=1&foo=2 (duplicate keys)
    • arrayFormatSeparator (string, default: ','): The character used when arrayFormat is 'separator'.
    • sort (Function | boolean, default: true): Enables sorting of keys. Use a custom function or false to disable.
    • parseNumbers (boolean, default: false): If true, numeric values are parsed as number types.
    • parseBooleans (boolean, default: false): If true, boolean values are parsed as boolean types.
    • types (object, default: {}): A schema for explicit type declarations or custom transformation functions. This takes precedence over parseNumbers, parseBooleans, and arrayFormat.
  11. Configure .stringify() options

    main

    The .stringify(object, options?) method accepts several options:

    • strict (boolean, default: true): Strictly encode URI components.
    • encode (boolean, default: true): URL encode keys and values.
    • arrayFormat (string, default: 'none'): Defines how arrays are serialized (e.g., 'bracket', 'index', 'comma', 'separator', 'bracket-separator', 'colon-list-separator', 'none').
    • arrayFormatSeparator (string, default: ','): The character used when arrayFormat is 'separator'.
    • sort (Function | boolean, default: true): Enables sorting of keys. Use a custom function or false to disable.
    • skipNull (boolean, default: false): Skip keys where the value is null.
    • skipEmptyString (boolean, default: false): Skip keys where the value is an empty string ''.
    • replacer (function, default: undefined): A function similar to JSON.stringify's replacer, used to transform values before stringification. Returning undefined omits the key.