Get Country name from Country code using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get Country name from Country code using JavaScript #

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.

index.js
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:

  • translate a region code to the country's name
  • translate a language code to the language's name
  • translate a currency code to the currency's display name
The first parameter the 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 available 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.

If you need the country names in a different language, change the locale when creating the object.

index.js
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.

index.js
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.

index.js
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.