Skip to main content

parseCommaSeparated()

parseCommaSeparated<T>(value, parser): T[]

Parses a comma-separated string using a custom parser function.

note

Does not trim values automatically. Empty string returns [''].


Type Parametersโ€‹

T: Tโ€‹

The type of parsed values.


Parametersโ€‹

value: stringโ€‹

The comma-separated string to parse.

parser: (item) => Tโ€‹

The function to transform each value.


Returns: T[]โ€‹

The array of parsed values.


Sinceโ€‹

1.0.0


Exampleโ€‹

parseCommaSeparated('1,2,3', Number);
// => [1, 2, 3]

parseCommaSeparated('a,b,c', (x) => x.toUpperCase());
// => ['A', 'B', 'C']

parseCommaSeparated(' a , b ', (x) => x.trim());
// => ['a', 'b']

How it works?โ€‹

Parses a comma-separated string using a custom parser function.

Processing Flowโ€‹

Common Inputsโ€‹

ValueParserResult
'1,2,3'Number[1, 2, 3]
'a,b,c'x => x.toUpperCase()['A', 'B', 'C']
' a , b 'x => x.trim()['a', 'b']
''x => x['']

Use Casesโ€‹

Parse environment variables ๐Ÿ“Œโ€‹

Split comma-separated config values into arrays. Essential for parsing ALLOWED_ORIGINS or FEATURE_FLAGS from env files.

const origins = parseCommaSeparated(process.env.ALLOWED_ORIGINS, (s) => s.trim());
// ['https://app.com', 'https://api.com', 'http://localhost:3000']

Handle user input listsโ€‹

Parse user-submitted tags or recipients from form inputs.

const recipients = parseCommaSeparated('alice@co.com, bob@co.com, charlie@co.com', (e) => e.trim().toLowerCase());
// ['alice@co.com', 'bob@co.com', 'charlie@co.com']

Transform values during parsingโ€‹

Apply transformations to each parsed value in a single pass.

const ids = parseCommaSeparated('1, 2, 3, 4', (s) => parseInt(s.trim(), 10));
// [1, 2, 3, 4]