Is there a way to get the country code (Alpha-2) from a country name in JavaScript?
Asked
Active
Viewed 7,561 times
2
-
Where are you getting the country name from? A normalized list of some sort? – Austin T French Sep 10 '20 at 12:39
-
Not by default, but you can build something yourself or use some kind of lookup service. – Mark Baijens Sep 10 '20 at 12:40
-
@AustinTFrench The purpose is that a user can input country in a form, when they submit that form the country input should result in a country code in the backend that is sent to another system to gather data.. im building a script for it and thought if there was a way to get this info without needing to create a custom function for it. – Christian Sep 10 '20 at 12:52
1 Answers
3
You can use this API https://restcountries.eu/
fetch("https://restcountries.eu/rest/v2/name/kenya").then(resp=>{
return resp.json();
}).then(json=>{
console.log(json[0].alpha2Code);
})

Shubham Srivastava
- 1,807
- 1
- 10
- 17
-
`v2` API is not working anymore, here's the updated API link: `https://restcountries.com/v3.1/name/kenya` – Asad ullah Jun 26 '23 at 09:15