brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Intl.ListFormat joins lists the way the language does

Web-Development
~/tips/tip-javascript-intl-listformat

const cities = ["Leiden", "Delft", "Utrecht"];

Joins an array into a readable sentence list using the rules of a language.

Joining names with ', ' and special-casing the last one is code I have written too often. The separator and the last word differ per language, and Intl.ListFormat knows them.

Create a formatter for a locale and call format() with an array of strings:

const cities = ["Leiden", "Delft", "Utrecht"];

new Intl.ListFormat("nl", { type: "conjunction" }).format(cities);
// "Leiden, Delft en Utrecht"

new Intl.ListFormat("en", { type: "disjunction" }).format(cities);
// "Leiden, Delft, or Utrecht"

new Intl.ListFormat("en-GB").format(cities);
// "Leiden, Delft and Utrecht"

The English result with en has a comma before “or”, while Dutch and British English leave it out. That is the kind of detail a hand-written join forgets. The type can be conjunction (and), disjunction (or) or unit, and style can be long, short or narrow. With unit and narrow the items are just listed without a joining word. MDN lists it as widely available since April 2021.

Short lists behave sensibly: two items give “Leiden and Delft”, one item gives just “Leiden”, and an empty array gives an empty string.

Caveats: it formats what you give it. The items themselves are not translated, so the names in the array still have to be in the right language. An unknown type throws a RangeError. The punctuation rules differ per locale, so look at the output once for every locale you ship.

Further reading: MDN: Intl.ListFormat

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link