Get Country name from Country code using JavaScript

avatar

Borislav Hadzhiev

Wed Jan 19 20222 min read

banner

Photo by Zi Nguyen

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

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.