Last updated: Mar 6, 2024
Reading timeΒ·2 min
Use the Intl.DisplayNames()
constructor to get a country name from a country
code.
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 the properties that are available on the options
object
in
this section
of 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.
If you need the country names in a different language, change the locale when creating the object.
const regionNames = new Intl.DisplayNames(['de'], { type: 'region', }); console.log(regionNames.of('US')); // ποΈ "Vereinigte Staaten" console.log(regionNames.of('DE')); // ποΈ "Deutschland" console.log(regionNames.of('KR')); // ποΈ "SΓΌdkorea" console.log(regionNames.of('CA')); // ποΈ "Kanada"
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.
You can learn more about the related topics by checking out the following tutorials: