How to Add Unicode Character to a JavaScript String?

To insert a Unicode character into a JavaScript string, you can do either of the following:

Using Unicode Escape Sequence

You can escape a Unicode code point using the unicode escape sequence "\u{XXXXXX}" (where "X" represents 1-6 hexadecimal digits in the range of U+0000 to U+10FFFF, which covers the entirety of Unicode).

For example, to insert the fox emoji (i.e. U+1F98A) into a JavaScript string, you would do the following:

// ES6+
const fox = 'fox: \u{1F98A}'; // 'fox: 🦊'

console.log(fox);

In older versions of JavaScript, however, you can only specify (exactly) 4 hexadecimal digits using the unicode escape sequence "\uXXXX" (where "X" represents characters in the range of U+0000 to U+FFFF, which only covers the Unicode Basic Multilingual Plane).

Unicode has evolved to include more characters that lie beyond the BMP (Basic Multilingual Plane). Those characters are represented by "surrogate pairs", code point of which you cannot add directly in older versions of JavaScript. To represent such characters correctly, you would need to use two adjoined unicode escape sequences (i.e. two code points; high surrogate and low surrogate, that make up the character surrogate pair).

For example, to display the fox emoji in older versions of JavaScript, you would use the character's high surrogate and low surrogate adjoined, like so:

const fox = 'fox: \uD83E\uDD8A'; // 'fox: 🦊'

console.log(fox);

Using String.fromCodePoint()

You can add a Unicode code point to a JavaScript string by using the String.fromCodePoint() method. It accepts a sequence of code points (represented in decimal, hexadecimal, octal, etc.) as argument.

For example, you can use the decimal code point to display the fox emoji like so:

// ES6+
const fox = `fox: ${String.fromCodePoint(129418)}`; // 'fox: 🦊'

console.log(fox);

Similarly, you can use the hexadecimal code point to display the fox emoji like so:

// ES6+
// using hexadecimal code point
const fox = `fox: ${String.fromCodePoint(0x1F98A)}`; // 'fox: 🦊'

console.log(fox);

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.