Skip to main content Accessibility Feedback

Getting emoji from country codes with vanilla JavaScript

I’m making some updates to how my Pricing Parity/location-based pricing messaging is displayed for my courses.

One of the biggest changes is switching from a big image of the country flag to an inline emoji. Today, I wanted to share a small vanilla JS snippet I found to get the correct flag emoji for a country code.

This code was shared by Jorik, an engineer at Google…

/**
 * Get the flag emoji for the country
 * @link https://dev.to/jorik/country-code-to-flag-emoji-a21
 * @param  {String} countryCode The country code
 * @return {String}             The flag emoji
 */
function getFlagEmoji (countryCode) {
	let codePoints = countryCode.toUpperCase().split('').map(char =>  127397 + char.charCodeAt());
	return String.fromCodePoint(...codePoints);
}

To use it, you pass in the two-letter country code (in upper or lower case) you want the flag for…

// returns "🇺🇸"
getFlagEmoji('us');

// returns "🇳🇬"
getFlagEmoji('ng');

// returns "🇮🇹"
getFlagEmoji('IT');

Jorik explains…

The flag emoji is a combination of the two unicode region characters, located at unicode position 127462 for the letter A.

The getFlagEmoji() snippet maps the two letters in the country code to corresponding unicode characters, and returns them as a string.

To learn what each line in the code does, go read his full article at dev.to.