DEV Community

Evan Winter
Evan Winter

Posted on

TIL – List formatting with Intl.ListFormat

Intl.ListFormat is an object for formatting lists into human-friendly language.

It takes an array of values and turn it into a comma-separated string list with an 'and', 'or' or '&' (and other languages' equivalents) before the last word.

Basic usage:

let fruit = ['Apples', 'Oranges', 'Bananas'];
let formatter = new Intl.ListFormat('en');
let result = formatter.format(fruit);
// Result:  'Apples, Oranges, and Bananas'
Enter fullscreen mode Exit fullscreen mode

With 'or' instead of 'and':

let list = ['Chicago', 'Minneapolis', 'Madison'];
let formatter = new Intl.ListFormat('en', { type: 'disjunction' });
let result = `Are you in ${formatter.format(list)}?`;
// Result: 'Are you in Chicago, Minneapolis, or Madison?'
Enter fullscreen mode Exit fullscreen mode

One downside is that you can't remove the Oxford comma, the one before 'and'/'or'/'&'.

MDN Docs: ('https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat')

Top comments (0)