Country Flags
Unicode allows flags to be displayed. Also, the ISO 3166-1 alpha-2 code determines a country with 2 letters. Can the two be combined? From FR to 🇫🇷.
YES
In fact, there are a multitude of examples online. You just need to know. The following function converts the parameter ISO 3166-1 alpha-2 code into an emoji:
function getFlagEmoji(countryCode) {
const codePoints = countryCode
.toUpperCase()
.split('')
.map(char => 127397 + char.charCodeAt());
return String.fromCodePoint(...codePoints);
}
(read from post https://dev.to/jorik/country-code-to-flag-emoji-a21)
We can notice three things:
- the code used to generate a flag is contiguous. FR gives the flags (F) 70 + 127 397 and (R) 82 + 127 397. Unicode uses special characters to encode flags, with one special character per letter.
- The font used is the one provided by the OS. The output character can be used directly.
- The reverse is also easy: we take the input as parameter and substract 127 397 to each caracter to get the country code
This solution keeps flag management logic light and simple, and there’s no need for additional code! No dependencies, no svgs.
The biggest flaw is the lack of Windows support 😳
But otherwise, it’s ok.. There are of course things to optimize right and left. For two characters and an emoji, it’s still good enough. Simple.