19

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.

ulmas
  • 517
  • 1
  • 5
  • 15

3 Answers3

48

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

trefnis
  • 496
  • 5
  • 2
  • 3
    Seems like Firefox added support as of FF86, but still no support for Safari. As of Apr 2021 – Patrick Apr 21 '21 at 06:59
  • 10
    how to reverse this ? "United States" to "US" ? – Gel Oct 11 '21 at 16:24
  • Now supported in the latest versions of all browsers except IE, 88% of users should have access to this globally: https://caniuse.com/?search=Intl.DisplayNames – fredrivett Nov 26 '21 at 11:16
  • 1
    Nice! btw Safari support has landed 17 May 2022. – Neurotransmitter Jul 01 '22 at 23:05
  • @Gel See [my answer here](https://stackoverflow.com/a/75467239/2203482) for the reverse of this, e.g. `English` ➜ `en`, `Chinese` ➜ `zh`, etc. – Hat Feb 16 '23 at 02:32
6

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

Tarmo
  • 3,851
  • 2
  • 24
  • 41
2

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";
...
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 1
    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... – vittorio Apr 06 '22 at 14:00