Aller au contenu principal

parseCommaSeparated()

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

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

remarque

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]