Turn a country code into an emoji flag (US ➡️ 🇺🇸)
Tags: webdev, go, typescript, php
Published: 2024-05-21 05:38:31

Flag emojis are a fun and visual way to represent countries and regions. These emojis are part of the [Unicode standard](https://en.wikipedia.org/wiki/Regional_indicator_symbol) and are created using a pair of regional indicator symbols.

In this article, we will explore how to convert 2-letter [ISO 3166-1](https://en.wikipedia.org/wiki/ISO_3166-1) country codes to flag emojis in **Go**, **PHP** and **TypeScript**.

## Understanding Flag Emojis

Flag emojis are composed of two Unicode characters, each representing a regional indicator symbol. For example, the flag of the United States (🇺🇸) is created by placing the Unicode points for the regional indicators "🇺" and "🇸" next to each other.

These Unicode points start at [U+1F1E6](https://www.compart.com/en/unicode/U+1F1E6) (regional indicator symbol letter "A") and continue to [U+1F1FF](https://www.compart.com/en/unicode/U+1F1FF) (regional indicator symbol letter "Z").

## The formula 🤓

The formula to convert a letter to its corresponding regional indicator symbol is:

```
Unicode point = <ASCII code of letter> − 65 + 127462
```

- `65` is a decimal value of letter "A"
- `127462` is a decimal value of [`U+1F1E6`](https://www.compart.com/en/unicode/U+1F1E6)

Since `127462 - 65 = 127397 = 0x1F1A5`, we will use `0x1F1A5` in further calculations.

## Conversion in Go 👨🏻‍💻

Here is an example in Go (Golang) to convert an ISO 3166-1 country code to a flag emoji. This code snippet normalizes the input to uppercase and then converts each character to its corresponding regional indicator symbol. For simplicity, it doesn't perform any validation so you should make sure it is a valid 2-letter code first.

```go
package main

import (
	"fmt"
	"strings"
)

func country2flag(countryCode string) string {
	var flagEmoji strings.Builder
	countryCode = strings.ToUpper(countryCode)
	for _, char := range countryCode {
		flagEmoji.WriteRune(rune(char) + 0x1F1A5)
	}
	return flagEmoji.String()
}

func main() {
	fmt.Println(country2flag("pl"))  // 🇵🇱
	fmt.Println(country2flag("JP"))  // 🇯🇵
	fmt.Println(country2flag("us"))  // 🇺🇸
	fmt.Println(country2flag("EU"))  // 🇪🇺
}
```

### Explanation 👨🏻‍🏫

1. **Normalization**: The input country code is converted to uppercase using `strings.ToUpper()`.
2. **String Builder**: A `strings.Builder` is used to efficiently build the resulting flag emoji string.
3. **Character Processing**: Each character of the uppercase country code is processed: `rune(char) + 0x1F1A5`: Converts the character to its corresponding regional indicator symbol by adding `0x1F1A5` (127397).
4. **Appending Characters**: The resulting regional indicator symbols are appended to the `strings.Builder`.
5. **Returning the Result**: The `String()` method of `strings.Builder` is called to get the final flag emoji string.

## Conversion in PHP 🐘

Using `preg_replace_callback` allows to replace each character in a string using a custom callback:

```php
function country2flag(string $countryCode): string
{
    return preg_replace_callback(
        '/./',
        static fn (array $m) => chr(ord($m[0]) + 0x1F1A5),
        strtoupper($countryCode)
    );
}

echo country2flag('pl'); // 🇵🇱
echo country2flag('JP'); // 🇯🇵
echo country2flag('us'); // 🇺🇸
echo country2flag('EU'); // 🇪🇺
```

## Conversion in TypeScript 😎

This example uses a combination of `split` and `join` to process each character individually.

```typescript
function country2flag(countryCode: string): string {
    return countryCode
        .toUpperCase()
        .split('')
        .map(char => String.fromCodePoint(char.charCodeAt(0) + 0x1F1A5))
        .join('');
}

console.log(country2flag('pl')); // 🇵🇱
console.log(country2flag('JP')); // 🇯🇵
console.log(country2flag('us')); // 🇺🇸
console.log(country2flag('EU')); // 🇪🇺
```

## Conclusion

🤗 Converting ISO 3166-1 country codes to flag emojis can be fun and straightforward in **Go**, **PHP** and **TypeScript**! By understanding how regional indicator symbols work and using simple character manipulation, you can easily generate these emojis programmatically in any other language ✨.

🛠️ Whether you're building a web application or a server-side script, this technique can add a fun and informative visual element to your project.

☝🏻 Please note that the appearance and availability of the flag emojis might vary between systems and locale.

**Feel free to post snippets in your favourite programming language in the comments!**

This article is based on the snippet I posted on GitHub Gist 3 years ago: 
{% embed https://gist.github.com/IonBazan/b0d6165b2dfa1afc6329ea885e1feeb5 %}