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.DisplayNames gives country, language and currency names in any language

Javascript
~/tips/tip-js-intl-displaynames-countries

const regions = new Intl.DisplayNames(["nl"], { type: "region" });

Turn codes like DE or EUR into readable names without a translation file.

A country picker needs names for about 250 codes, in every language the site supports. Instead of a big JSON file, I can ask the browser, which already ships those names.

const regions = new Intl.DisplayNames(["nl"], { type: "region" });
regions.of("DE"); // "Duitsland"
regions.of("BE"); // "België"

new Intl.DisplayNames(["en"], { type: "language" }).of("nl");   // "Dutch"
new Intl.DisplayNames(["en"], { type: "currency" }).of("EUR");  // "Euro"
new Intl.DisplayNames(["de"], { type: "script" }).of("Cyrl");

The first argument is the language you want the names in, and type says what kind of code you pass: region for ISO country codes, language, currency, script, calendar or dateTimeField. The same code then gives you “Germany”, “Allemagne” or “Duitsland” depending on the language you created the object with.

A language switcher is a nice use: show each option in its own language with new Intl.DisplayNames([code], { type: "language" }).of(code), so a Dutch visitor on an English page still finds “Nederlands”.

The names come from the browser’s locale data, so they can differ slightly between browsers and versions, and you cannot edit a name you disagree with. For a well-formed code the data has no name for, of() returns the code itself by default; set fallback: "none" to get undefined instead. Support: Chrome 81, Firefox 86 and Safari 14.1.

Further reading: MDN: Intl.DisplayNames

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link