Borislav Hadzhiev
Wed Jan 19 2022·2 min read
Photo by Zi Nguyen
Use the Intl.DisplayNames()
constructor to get a country name from a country
code, e.g. new Intl.DisplayNames(['en'], {type: 'region'}).of('US')
. The
of()
method on the returned object takes a code as a parameter and returns a
string based on the provided locale.
const regionNames = new Intl.DisplayNames( ['en'], {type: 'region'} ); console.log(regionNames.of('US')); // 👉️ "United States" console.log(regionNames.of('GB')); // 👉️ "United kingdom" console.log(regionNames.of('DE')); // 👉️ "Germany" console.log(regionNames.of('AU')); // 👉️ "Australia"
The Intl.DisplayNames() constructor returns an object we can use to:
Intl.DisplayNames()
constructor takes is a string containing a BCP 47 language tag, or an array of such strings.The second parameter is an options
object.
You can read about all of the available properties on the options
object in
the
MDN docs.
The
Intl.DisplayNames.of()
method takes a country code as a parameter and returns a string based on the
locale and the provided parameters when instantiating the Intl.DisplayNames
object.
You can change the locale when creating the object if you need the country names in a different language.
const regionNames = new Intl.DisplayNames( ['de'], {type: 'region'} ); console.log(regionNames.of('US')); // 👉️ "Vereinigte Staaten" console.log(regionNames.of('DE')); // 👉️ "Deutschland"
Here is an example that shows how to get a language name from a language code.
const regionNames = new Intl.DisplayNames( ['en'], {type: 'language'} ); console.log(regionNames.of('en-US')); // 👉️ "American English" console.log(regionNames.of('en-GB')); // 👉️ "British English" console.log(regionNames.of('de-DE')); // 👉️ "German (Germany)"
We changed the value of the type
property in the options
object and got the
display names for the language codes.
You can also use this approach to convert a currency code to the currency's display name for the specific locale.
const regionNames = new Intl.DisplayNames( ['en'], {type: 'currency'} ); console.log(regionNames.of('USD')); // 👉️ "US Dollar" console.log(regionNames.of('EUR')); // 👉️ "Euro" console.log(regionNames.of('JPY')); // 👉️ "Japanese Yen"
We set the type
property to currency
and got the display names of the
currencies based on the provided locale.