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' }