How to get country name from country code in javascript

17,745

Solution 1

You can use Intl.DisplayNames for this purpose, standard JS api, but not with full browser support yet (needs polyfills for Firefox & Safari as of January 2021).

Usage:

let regionNames = new Intl.DisplayNames(['en'], {type: 'region'});
regionNames.of('US');  // "United States"

Details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames

Solution 2

I think there is nothing like that build into the Javascript standard library, but as always, there is an NPM library for it: https://www.npmjs.com/package/i18n-iso-countries

Solution 3

If you search the internet hard enough, you might find a GitHub project or other piece of code that does this. But honestly your best bet is just to find the list of abbreviations and country names and build your own object. It really shouldn't take more than a half hour, at most

var atoc = {};
atoc.us = "United States";
atoc.uk = "United Kingdom";
...
Share:
17,745
Ulmasbek rakhmatullaev
Author by

Ulmasbek rakhmatullaev

Updated on July 22, 2022

Comments

  • Ulmasbek rakhmatullaev
    Ulmasbek rakhmatullaev almost 2 years

    I am building a weather website, and I want to display the country name for the given location but my API request to openweathermap only returns country code. So is there a way to convert the country code to country name from javascript itself or I need to make one more API call to other url which will convert me the code to name.

  • Patrick
    Patrick about 3 years
    Seems like Firefox added support as of FF86, but still no support for Safari. As of Apr 2021
  • Gel
    Gel over 2 years
    how to reverse this ? "United States" to "US" ?
  • fredrivett
    fredrivett over 2 years
    Now supported in the latest versions of all browsers except IE, 88% of users should have access to this globally: caniuse.com/?search=Intl.DisplayNames
  • Ruben Verster
    Ruben Verster about 2 years
  • vittorio
    vittorio about 2 years
    As a rule of thumbs, I prefer avoid doing again something that others have done. Beside, filling the +195 countries without errors might take more than 30 minutes...