When developing features such as a country selector, a currency picker, or a language switcher, you often need to display the names of countries, currencies, and languages translated into the user's language. JavaScript's Intl.DisplayNames
object is a handy tool for this purpose.
To use Intl.DisplayNames
, create a new instance by specifying the user's current language and the type of display names you need. Then, retrieve the translated display name using the of()
method. In the following example, we generate the display name for the US region in both English and German.
const regionEnglish = new Intl.DisplayNames("en", { type: "region" });
regionEnglish.of("US"); // United States
const regionGerman = new Intl.DisplayNames("de", { type: "region" });
regionGerman.of("US"); // Vereinigte Staaten
By altering the type
parameter in the Intl.DisplayNames
constructor, you can retrieve display names for different categories such as languages or currencies.
const lang = new Intl.DisplayNames("en", { type: "language" });
lang.of("en-US"); // American English
lang.of("fr"); // French
const currency = new Intl.DisplayNames("en", { type: "currency" });
currency.of("USD"); // US Dollar