Search code examples
javascripthtmlcss

How to get country flag code given the name of the Country?


I want to display flag of a country in a <td> based on the name of the country.

I have 50 countries and want to populate the flags based on the name of the country in a <td>.

I can place a simple image in a page like this:

<img src="https://lipis.github.io/flag-icon-css/flags/4x3/gb.svg" style="height:100">

This Javascript code below does what I need it to do: //Change the code for the country

var stringCountryCode = getCountryCode(cName);

  var str = "https://lipis.github.io/flag-icon-css/flags/4x3/gb.svg";
  var res = str.replace(/gb/g, stringCountryCode );
  document.getElementById("demo").innerHTML = res;

The only problem is how do I get this code based on the country name.

function getCountryCode(countryName) {


}

Solution

  • First, shout out to @mrkn0007 and to @Barmar for having some of the pieces.

    I would actually approach it differently by having the URL output:

    var countrycodedict = {
        'United States': 'us'
        // ... fill in
    };
    
    function getCountryCode(countryName) {
        return 'https://lipis.github.io/flag-icon-css/flags/4x3/'+countrycodedict[countryName]+'.svg';
    }
    
    document.getElementById("demo").src = getCountryCode(cName);
    

    In this case, instead of trying to set it by doing a bit of go-arounds, you can simply make a function then set the src to the output of the function.

    See this link for how to set src for images.