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.
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β
| Input | Pair Sep | KV Sep | Result |
|---|---|---|---|
'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' }
Parse cookie stringsβ
Extract key-value pairs from cookie headers.
const cookies = parseKeyValuePairs('session=abc123; theme=dark; lang=en', '; ');
// { session: 'abc123', theme: 'dark', lang: 'en' }