29
loading...
This website collects cookies to deliver better user experience
const favoriteDogs = ['Corgi', 'German Shepherd', 'Goldendoodle'];
function formatList(list) {
if (!list?.length) {
return "";
}
if (list.length === 1) {
return list.toString();
}
if (list.length === 2) {
return list.join(' and ');
}
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
};
Intl.ListFormat
to have JavaScript do this heavy lifting for us.Intl.ListFormat
replaces formatList
with a couple of lines of code:const lf = new Intl.ListFormat('en');
lf.format(favoriteDogs);
// > Corgi, German Shepherd, and Goldendoodle
Intl.ListFormat
comes from Intl
, which is a built-in object that provides language-sensitive functions. We've provided en
(English) as the locales
argument, which formats the list based on the language or region.zh
for traditional Chinese and let it localize the conjunction and punctuation for us:const lf = new Intl.ListFormat('zh');
lf.format(['咖啡', '茶', '可樂']);
// > 咖啡、茶和可樂 (Coffee, tea and coke)
options
argument that has a style
and type
property. style
is the length of the output and can be long
(the default), short
or narrow
:new Intl.ListFormat('en', { style: 'short' }).format(favoriteDogs);
// > Corgi, German Shepherd, & Goldendoodle
new Intl.ListFormat('en', { style: 'narrow' }).format(favoriteDogs);
// > Corgi, German Shepherd, Goldendoodle
type
describes the list type, which is conjunction
(and-based) by default. It can be used to make our list disjunctive
or suitable for units:new Intl.ListFormat('en', { type: 'disjunction' }).format(favoriteDogs);
// > Corgi, German Shepherd, or Goldendoodle
new Intl.ListFormat('en', { type: 'unit' }).format(['6 feet', '2 inches']);
// > 6 feet, 2 inches
Intl.ListFormat
. There are a lot of other useful functions from Intl
, too; check them out at MDN.