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) {
}
Pure JS -- No External Library
function countryCodeToFlag(countryCode) {
// Validate the input to be exactly two characters long and all alphabetic
if (!countryCode || countryCode.length !== 2 || !/^[a-zA-Z]+$/.test(countryCode)) {
return 'π³οΈ'; // White Flag Emoji for unknown or invalid country codes
}
// Convert the country code to uppercase to match the regional indicator symbols
const code = countryCode.toUpperCase();
// Calculate the offset for the regional indicator symbols
const offset = 127397;
// Convert each letter in the country code to its corresponding regional indicator symbol
const flag = Array.from(code).map(letter => String.fromCodePoint(letter.charCodeAt(0) + offset)).join('');
return flag;
}
// Example usage:
console.log(countryCodeToFlag('us')); // Outputs: πΊπΈ
console.log(countryCodeToFlag('de')); // Outputs: π©πͺ
console.log(countryCodeToFlag('fr')); // Outputs: π«π·
The function countryCodeToFlag converts a two-letter country code, like "US" for the United States or "DE" for Germany, into the emoji flag of that country. Here's how it works in simple steps:
Every letter has a number associated with it in the computer's encoding system (Unicode). For example, 'A' is 65, 'B' is 66, and so on. There's also a starting point in Unicode for regional indicator symbols, which is 127462 for the letter 'A'. This is where the "offset" value of 127397 comes from in the function (127462 - 65 = 127397). To get the regional indicator symbol for each letter, the function adds this offset to the letter's Unicode number. So, for 'U' (which is 85 in Unicode), adding the offset gives us the Unicode number for the regional indicator symbol 'πΊ', and similarly for 'S' to get 'πΈ'.
Combine Symbols: After converting both letters, the function combines them to form the flag emoji. For "US", it combines 'πΊ' and 'πΈ' to make 'πΊπΈ'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With