Skip to content

Language sensitive list formatting in JavaScript

Occasionally, we have to generate comma separated lists like ‘Alice, Bob and Carol’ and ‘Alice, Bob or Carol’ from arrays. Instead of writing duct tape code using Array.join() or third-party libraries, we can use native Intl.ListFormat. It is part of the ECMAScript Internationalization API.

The Intl.ListFormat constructor accepts two parameters, locale and options, and returns an object. Use the locale to specify the language. Use options to set two key parameters, type and style. To generate and-based lists use type: conjunction and for or-based lists use type: disjunction. The possible values for style are long and short. In English locale, style: long with type: conjunction generates a list with and, whereas style: short generates a list with &.

The returned object exposes format() with which we can convert arrays to lists.

List with ‘and’ (conjunction)

const names = ["Alice", "Bob", "Carol", "Dan"];

const formatterEnLong = new Intl.ListFormat("en", {
style: "long",
type: "conjunction",
});
console.log(formatterEnLong.format(names));
// Output: Alice, Bob, Carol, and Dan

const formatterEnShort = new Intl.ListFormat("en", {
style: "short",
type: "conjunction",
});
console.log(formatterEnShort.format(names));
// Output: Alice, Bob, Carol, & Dan

const formatterFr = new Intl.ListFormat("fr", {
style: "long",
type: "conjunction",
});
console.log(formatterFr.format(names));
// Output: Alice, Bob, Carol et Dan

List with ‘or’ (disjunction)

const names = ["Alice", "Bob", "Carol", "Dan"];

const formatterEn = new Intl.ListFormat("en", {
style: "long",
type: "disjunction",
});
console.log(formatterEn.format(names));
// Output: Alice, Bob, Carol, or Dan

const formatterFr = new Intl.ListFormat("fr", {
style: "long",
type: "disjunction",
});
console.log(formatterFr.format(names));
// Output: Alice, Bob, Carol ou Dan

Intl.ListFormat is supported in all modern browsers and Node.js v13+.

Responses

1 Retweet

I’ll be available for long-term projects from July 2023. Meanwhile, open for smaller projects.

Get in touch