Ahmet ALMAZ Doom Face

Ahmet ALMAZ

Full Stack Developer from Türkiye 🇹🇷

How to Convert Country Code to Flag Emoji in JavaScript

/ 2 min / 373 words / --- views

I recently came across neon.techthis tutorial by www.paulie.devPaul on how to build a custom analytics tool using Astro, Vercel Edge Functions, and Neon. I was impressed by the simplicity of the tutorial and decided to give it a try.

In the tutorial, Paul used the www.npmjs.com@vercel/edge npm package to build the Edge Function. It comes with an easy way to get the country flag emoji. However, I wanted to use the workers.cloudflare.comCloudflare Workers to build the Edge Function and needed a way to get the country flag emoji as well.

If you dig deep into Vercel’s source code, you will find where the magic happens. They have a github.comfunction that converts the country code to flag emoji .

I did a little bit of research on how to convert country code to flag emoji in JavaScript and found this dev.toDev.to article . In the comment section, people started to compete on who can write the shortest and fastest code to convert country code to flag emoji. I decided to use the code from dev.tothis comment .

export default function getFlagEmoji(countryCode: string) {
return [...countryCode.toUpperCase()]
.map((char) => String.fromCodePoint(127397 + char.charCodeAt(0)))
.reduce((a, b) => `${a}${b}`)
}

And according to jsperf.appthis benchmark , it is the fastest code to convert country code to flag emoji.

# Here’s how the code works:

  1. Input Parameter:

    • The function takes a countryCode parameter, which is expected to be a string representing a country code (e.g., “TR” for the country of Türkiye).
  2. Conversion to Uppercase:

    • countryCode.toUpperCase(): The provided country code is converted to uppercase to ensure consistency and avoid case-related issues.
  3. Mapping Characters to Emoji Code Points:

    • [...countryCode.toUpperCase()]: The string is spread into an array of individual characters.
    • .map((char) => String.fromCodePoint(127397 + char.charCodeAt(0))): Each character’s Unicode code point is calculated and converted to a string using String.fromCodePoint. The magic number 127397 is added to the code point, as this is the offset for regional indicator symbols to get the corresponding flag emoji.
  4. Reducing to a Single String:

    • .reduce((a, b) => ${a}${b}): The array of emoji characters is reduced to a single string by concatenating each emoji.
  5. Return Value:

    • The function returns the final string, which is the concatenation of emoji characters representing the country’s flag.

# Example Usage:

const usFlagEmoji = getFlagEmoji('TR')
console.log(usFlagEmoji) // 🇹🇷

# Conclusion

I hope you learned a thing or two about converting country code to flag emoji in JavaScript.