When building internationalized applications, it's common to work with ISO country codes like BE
, NL
, or FR
. But how do you dynamically display the full translated country names in JavaScript without maintaining a huge manual list?
Thankfully, modern JavaScript provides a simple and powerful API: Intl.DisplayNames
.
Introduced in modern browsers, Intl.DisplayNames
can localize region names (like countries) automatically. Here's a quick example:
const locale = 'fr'; // Target language (e.g., 'en', 'fr', 'nl', ...)
const countryCode = 'BE'; // ISO 3166-1 alpha-2 country code
const regionNames = new Intl.DisplayNames([locale], { type: 'region' });
console.log(regionNames.of(countryCode));
// Output: 'Belgique'
locale
determines the language of the result.type: 'region'
tells JavaScript that we are translating a region (country).- The result adapts automatically based on the given locale.
Another example:
const regionNames = new Intl.DisplayNames(['en'], { type: 'region' });
console.log(regionNames.of('NL'));
// Output: 'Netherlands'
Intl.DisplayNames
is supported in (see here):
- Chrome 71+
- Edge 79+
- Firefox 78+
- Safari 14+
- Node.js 14+
If you target modern browsers or Node.js, you can use it safely today.
For older browsers, consider fallback methods like hardcoded maps or libraries such as i18n-iso-countries
.
To make it reusable, you can wrap it like this:
function getCountryName(code, locale = 'en') {
const regionNames = new Intl.DisplayNames([locale], { type: 'region' });
return regionNames.of(code);
}
// Usage
console.log(getCountryName('FR', 'fr')); // 'France'
console.log(getCountryName('DE', 'en')); // 'Germany'
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.