BBizKit

query.parse

v0.1.0 latest

Parse a URL query string into a key-value record, handling both WHATWG (+) and RFC 3986 (%20) space encoding.

query-stringparsingurlhttpencoding

Parse a URL query string into a key-value record, handling both WHATWG (+) and RFC 3986 (%20) space encoding.

Signature

function parse(qs: string): Record<string, string | string[]>

Problem

URL query strings arrive from HTTP requests, browser APIs, and third-party services with inconsistent encoding conventions. Duplicate keys need array handling. Manual split-and-decode loops are error-prone (malformed percent-encoding, + vs %20, leading ? removal).

How It Works

Handles both + (WHATWG) and %20 (RFC 3986) space encoding transparently. Duplicate keys are automatically collected into arrays. Leading ? is stripped if present. Malformed percent-encoding falls back to the raw string.

Boundaries

  • Never returns null — returns {} for empty/whitespace input.
  • Throws TypeError for non-string input.
  • Keys with no = sign get an empty string value.
  • Empty keys (after decoding) are silently skipped.
  • Single value per key → string; multiple values → string[].

Replaces

Common boilerplate this function replaces:

const params = {}; qs.split('&').forEach(pair => { const [k, v] = pair.split('='); params[decodeURIComponent(k)] = decodeURIComponent(v); });

Examples

query.parse("?a=1&b=hello+world");  // { a: "1", b: "hello world" }
query.parse("a=1&a=2&a=3");  // { a: ["1", "2", "3"] }
query.parse("key");  // { key: "" }
query.parse("");  // {}
query.parse("?");  // {}

Standards

Caveats

  • Malformed percent-encoding (e.g. %ZZ) falls back to the raw string rather than throwing.
  • Empty keys are silently skipped, not preserved.

FAQ

How to parse a URL query string in JavaScript?

query.parse('?a=1&b=2') returns { a: '1', b: '2' }. Handles both + and %20 space encoding.

How does query.parse handle duplicate keys?

Duplicate keys are collected into arrays: query.parse('a=1&a=2') returns { a: ['1', '2'] }.

Does query.parse handle the leading ? character?

Yes. The leading ? is stripped if present.

What happens with malformed percent-encoding?

Malformed sequences like %ZZ are preserved as-is rather than throwing an error.

How is query.parse different from URLSearchParams?

query.parse returns a plain object with automatic array handling for duplicate keys. URLSearchParams requires .getAll() for duplicates.