BBizKit

query.stringify

v0.1.0 latest

Serialize an object into a URL query string with configurable encoding (WHATWG or RFC 3986) and array mode.

query-stringserializationurlhttpencoding

Serialize an object into a URL query string with configurable encoding (WHATWG or RFC 3986) and array mode.

Signature

function stringify(obj: Record<string, unknown>, opt?: StringifyOptions): string

Type Definitions:

Problem

Serializing objects to query strings requires choosing between WHATWG form encoding (space → +) and RFC 3986 (space → %20), handling arrays (repeat keys vs brackets), and managing null/undefined values. URLSearchParams lacks array mode control and always uses WHATWG encoding.

How It Works

Supports two encoding modes: WHATWG form (space → +, default) and RFC 3986 (space → %20). Array values are serialized as repeated keys by default, or with [] suffix. null/undefined handling is configurable via skipNull.

Boundaries

  • Throws TypeError for non-object / null input.
  • Default encoding is whatwg-form (space → +).
  • null/undefined values are serialized as empty string unless skipNull: true.
  • Output does not include a leading ?.

Replaces

Common boilerplate this function replaces:

new URLSearchParams(obj).toString()

Examples

query.stringify({ a: "1", b: "hello world" });  // "a=1&b=hello+world"
query.stringify({ a: "1", b: "hello world" }, { encoding: "rfc3986" });  // "a=1&b=hello%20world"
query.stringify({ a: ["1","2"] }, { array: "brackets" });  // "a%5B%5D=1&a%5B%5D=2"
query.stringify({ a: "1", b: null }, { skipNull: true });  // "a=1"

Standards

Caveats

  • Default encoding is WHATWG form (+ for spaces), not RFC 3986. Use { encoding: 'rfc3986' } for percent-encoding.
  • Key ordering follows Object.keys() order unless sort: true is specified.

FAQ

How to serialize an object to a query string in JavaScript?

query.stringify({ a: '1', b: '2' }) returns 'a=1&b=2'. Supports WHATWG and RFC 3986 encoding.

How to use RFC 3986 encoding for query strings?

query.stringify(obj, { encoding: 'rfc3986' }) uses %20 for spaces instead of +.

How to serialize arrays in query strings?

Use { array: 'brackets' } for a[]=1&a[]=2, or default 'repeat' for a=1&a=2.

How to skip null values in query strings?

query.stringify(obj, { skipNull: true }) omits keys with null/undefined values.

Does query.stringify sort keys?

Not by default. Use { sort: true } for alphabetical key sorting.