Parse Query String into Object
parseQueryStringβ
Parses a query string (optionally starting with ?
) into a JavaScript object.
Supports arrays for duplicate keys, and can intelligently convert string values to primitives (numbers, booleans, null).
Importβ
import { parseQueryString } from 'nhb-toolbox';
import { getQueryStringAsObject } from 'nhb-toolbox';
import { queryStringToObject } from 'nhb-toolbox';
// All 3 alias for the same utility
Function Signatureβ
parseQueryString<QParams extends ParsedQueryGeneric>(query: string, parsePrimitives = true): QParams
Usage Examplesβ
- Basic
- With '?' Prefix
- Multiple Values
- No Primitive Parsing
- Null and Booleans
parseQueryString('a=1&b=hello');
// Returns: { a: 1, b: 'hello' }
parseQueryString('?token=abc&active=true');
// Returns: { token: 'abc', active: true }
parseQueryString('tag=js&tag=ts');
// Returns: { tag: ['js', 'ts'] }
parseQueryString('n=10&x=true', false);
// Returns: { n: '10', x: 'true' }
parseQueryString('opt=null&isTrue=false');
// Returns: { opt: null, isTrue: false }
API Referenceβ
Parametersβ
Name | Type | Description |
---|---|---|
query | string | The query string to parse (with or without starting ? ). |
parsePrimitives | boolean | Whether to parse primitive-like strings ("false" , "1" , "null" , etc). Defaults to true . |
For better type intellisense for the returned object, pass a generic type that extends to
ParsedQueryGeneric
Returnsβ
A JavaScript object (StrictObject
) where each key is a string and each value may be:
string
number
boolean
null
string[]
,number[]
,boolean[]
, ornull[]
Typesβ
type ParsedQueryGeneric = Record<string, NormalPrimitive | NormalPrimitive[]>;
Key Featuresβ
- Flexible Input: Accepts query strings with or without a leading
?
. - Arrays from Multiple Keys: If a key appears more than once, you get an array.
- Automatic Primitive Parsing: Converts
"1" β 1"
,"true" β true"
,"null" β null"
by default. - Safe: Does not touch or depend on the browserβs
window.location
.
Aliasesβ
This function is also exported as:
getQueryStringAsObject
queryStringToObject
Limitationsβ
- No Deep Objects: Does not generate nested objects for dotted or bracketed keys (e.g.,
a.b=1
stays flat). - Empty Key Handling: Keys without a value (e.g.,
foo&b=2
) will be parsed withfoo
as an empty string""
. - No Key Decoding Customization: Uses standard URL decoding.
Notesβ
- Type Guessing: Primitive parsing is based on string matching;
"012"
becomes number12
, not"012"
unlessparsePrimitives = false
. - Setting
parsePrimitives: false
is useful when you want all values as strings, like in typical form posts. - Arrays are always returned for duplicate keys, regardless of primitive type.
- All values are
string
unless parsing is enabled (default).
Recommended Use Casesβ
- Parsing URLs or query strings in client-side and server-side environments.
- Reading user input or redirects where the string isnβt available on
window.location.search
. - Back-end parsing of GET query strings for API endpoints.
Conclusion:
parseQueryString
turns any query string into a highly usable JavaScript object, supporting advanced parsing and multi-value keys. It works with any string input, making it ideal for shared or non-browser environments.
parseQueryStringLiteralβ
Parses a literal query string (optionally starting with ?
) into a strictly typed JavaScript object.
This function is designed for use with literal string types to provide maximum TypeScript type safety and inference. It actually returns shows the runtime value as type!
Importβ
import { parseQueryStringLiteral } from 'nhb-toolbox';
import { literalQueryStringToObject } from 'nhb-toolbox';
// Both alias are for the same utility
Function Signatureβ
parseQueryStringLiteral<Q extends string>(query: Q): ParsedQuery<Q>
Usage Examplesβ
- Basic
- With '?' Prefix
- Multiple Values
- With Literal Types
parseQueryStringLiteral('a=1&b=hello');
// Returns: { a: '1', b: 'hello' }
// Typed as: { a: '1'; b: 'hello' }
parseQueryStringLiteral('?token=abc&active=true');
// Returns: { token: 'abc', active: 'true' }
// Typed as: { token: 'abc'; active: 'true' }
parseQueryStringLiteral('tag=js&tag=ts');
// Returns: { tag: ['js', 'ts'] }
// Typed as: { tag: ['js', 'ts'] }
const query = 'status=active&role=admin';
const result = parseQueryStringLiteral(query);
// result is typed as: { status: 'active'; role: 'admin' }
// With full type inference from the literal string
API Referenceβ
Parametersβ
Name | Type | Description |
---|---|---|
query | Q | The literal query string to parse (with or without ? ). |
Returnsβ
A strictly typed JavaScript object (ParsedQuery<Q>
) where each key is inferred from the query string and values are properly typed as:
string
for single valuesstring[]
for multiple values with the same key
Key Featuresβ
- Literal Type Inference: Provides maximum TypeScript type safety by inferring types from literal string inputs.
- Array Support: Automatically creates arrays for duplicate keys.
- Flexible Input: Accepts query strings with or without a leading
?
. - Strict Typing: Returns properly typed objects based on the input query string structure.
Aliasesβ
This function is also exported as:
literalQueryStringToObject
Comparison with parseQueryStringβ
Feature | parseQueryStringLiteral | parseQueryString |
---|---|---|
Type Inference | Infers from literal strings | Generic object type |
Primitive Parsing | No (returns strings only) | Yes (converts to numbers, booleans, null) |
Use Case | Literal string types with strict typing | Generic query strings with primitive conversion |
Performance | Faster (no type conversion) | Slower (due to primitive parsing) |
Recommended Use Casesβ
- When working with literal string types and maximum TypeScript type safety is required
- API endpoints with known, fixed query parameter structures
- Configuration parsing where the query structure is statically known
- When you need strict type inference without runtime type conversion
Notesβ
- String Values Only: Unlike
parseQueryString
, this function does not convert primitive values - all values remain as strings or string arrays. - Literal Types: For best TypeScript inference, use
as const
with your query strings. - No Browser Dependency: This function does not access or depend on
window.location.search
. - URL Decoding: Uses standard URL decoding for parameter values.
Example with Strict Typingβ
// With literal type inference
const configQuery = 'theme=dark&lang=en&features=search';
const config = parseQueryStringLiteral(configQuery);
// config is returned and typed as: { theme: 'dark'; lang: 'en'; features: 'search' }
// With multiple values
const filterQuery = 'category=books&category=movies&sort=rating';
const filters = parseQueryStringLiteral(filterQuery);
// filters is returned and typed as: { category: ['books', 'movies']; sort: string }
Conclusion:
parseQueryStringLiteral
provides maximum TypeScript type safety for parsing query strings from literal types, making it ideal for scenarios where the query structure is known at compile time and strict typing is required.