JavaScript video tutorial: Turning a country code into a flag

Little trick today to show you how to convert a character string containing the ISO code of a country into a flag without using images. Indeed, it is possible to rely on the unicode character table which has emoji to represent the flags of different countries. The small subtlety is that certain characters can be combined to give a new emoji. For example the emoji 👨 combined with the emoji 🏿 (skin color emoji) gives 👨🏿. It also works with “regional letter” emojis which, when combined, give country flags (🇫 + 🇷 gives 🇫🇷). This feature can be used to generate flags from a country code.

The logic

To begin with, we will cut our country code into a character array.

code.split('') // ["f" , "r"]

We will then obtain the UTF-16 code for each character.

letter.charCodeAt(0)  // [102, 114]

To obtain a number starting at 1 for the letter “a” and “A” (in the UTF-16 table, “a” is 97 and “A” is 65) we can recover the remainder of the division by 32. We recover also the code of the character located before the regional character 🇦 (0x1F1E6 – 1 = 0x1F1E5).

letter.charCodeAt(0) % 32 + 0x1F1E5 // [127467, 127479]

Once the codes of these emojis have been obtained, they can be converted back into characters using the method fromCodePoint.

String.fromCodePoint(emojiCode) // ['🇫', '🇷']

It is finally enough to join the 2 new characters to obtain our flag.

The final code

And this is what the final code looks like:

function isoToEmoji (code) {
  return code
    .split('')
    .map(letter => letter.charCodeAt(0) % 32 + 0x1F1E5)
    .map(emojiCode => String.fromCodePoint(emojiCode))
    .join('')
}

And the same code for PHP:

function isoToEmoji (string $code) {
    return implode(
        '', 
        array_map(
            fn ($letter) => mb_chr(ord($letter) % 32 + 0x1F1E5),
            str_split($code)
        )
    );
}

Nothing is displayed on Windows?!

On Windows chromium-based browsers (including Edge) do not display flags because the system font (Sego UI) does not support flag emojis. Until this problem evolves it is possible to use a polyfill which will load an alternative font which includes the flags to have a functional display.

LEAVE A REPLY

Please enter your comment!
Please enter your name here