Skip to main content

parseKeyValuePairs()

parseKeyValuePairs(input, pairSeparator, keyValueSeparator): Record<string, string>

Parses a string containing key-value pairs into an object.

๐Ÿ’Ž Why is this a Hidden Gem?

URLSearchParams is limited to URL-encoded & pairs. This handles connection strings, cookies, and any custom key=value format.

note

Trims keys and values automatically. Ignores malformed pairs (empty key or value).


Parametersโ€‹

input: string = ""โ€‹

The input string to parse.

pairSeparator: string = ","โ€‹

The separator between pairs. Defaults to ",".

keyValueSeparator: string = "="โ€‹

The separator between key and value. Defaults to "=".


Returns: Record<string, string>โ€‹

The object containing parsed key-value pairs.


Default Valueโ€‹

","

Default Valueโ€‹

"="

Sinceโ€‹

1.0.0


Exampleโ€‹

parseKeyValuePairs('name=John,age=30');
// => { name: 'John', age: '30' }

parseKeyValuePairs('name:John;age:30', ';', ':');
// => { name: 'John', age: '30' }

parseKeyValuePairs('key=value&other=data', '&');
// => { key: 'value', other: 'data' }

parseKeyValuePairs(' name = John , age = 30 ');
// => { name: 'John', age: '30' }

How it works?โ€‹

Parses a string containing key-value pairs into an object.

Processing Flowโ€‹

Common Inputsโ€‹

InputPair SepKV SepResult
'name=John,age=30',={name: 'John', age: '30'}
'name:John;age:30';:{name: 'John', age: '30'}
'key=value&other=data'&={key: 'value', other: 'data'}
' name = John ',={name: 'John'}

Use Casesโ€‹

Parse connection strings ๐Ÿ“Œโ€‹

Convert key=value strings into a configuration object. Perfect for parsing database connection strings or DSN formats.

const connection = parseKeyValuePairs('host=localhost;port=5432;db=myapp', ';');
// { host: 'localhost', port: '5432', db: 'myapp' }

Parse query stringsโ€‹

Handle standard URL query formats without using URLSearchParams. Useful for SSR or environments where URL APIs are unavailable.

const params = parseKeyValuePairs('page=1&sort=desc&filter=active', '&');
// { page: '1', sort: 'desc', filter: 'active' }

Extract key-value pairs from cookie headers.

const cookies = parseKeyValuePairs('session=abc123; theme=dark; lang=en', '; ');
// { session: 'abc123', theme: 'dark', lang: 'en' }