# «Dealing with surrogates in JavaScript

May 31, 2016 • ☕️ 3 min read

JavaScriptES6

So there are these great, but painful to program with thing, called “surrogate pairs”. If you’re reading this, you’re probably having trouble with them but hopefully after you read this, those troubles will be gone.

## What? Why?

“Surrogate pairs”, as they’re called, are a thing which lets you store characters with very high code points. JavaScript is encoded in what’s called “UTF-16”, which is a way of storing strings, this means every character has 16-bits to store a unique number to identify that single character. Now this may seem all fine and dandy, but then our good friend Unicode comes to cause problems. Unicode is the standard defining what number is associated with what character. If you speak English or some language with an alphabet that’s a rational size, this may seem fine, but unfortunately there’s more. English’s entire alphabet (upper and lower case) can be represented in just 52 numbers. Now compare this to Mandarin with around 50,000 characters. They are around 7,000 languages, many with their own alphabet. Additionally symbols and numerals all need their own number to be associated with. So how many characters can be stored in UTF-16? Well, take 16, 1s and convert to decimal:

$1111111111111111 = 2^{16} – 1 = 65535$

Seems like a lot until you realize there’s emojis, the amount of alphabets, numbers, and symbols. This adds up quick, and it wasn’t long before the encoding guys realized that 16-bits wasn’t enough. UTF-32 doesn’t have this problem, but keep in mind this uses 32 bits per character. The letter a would be: 00000000000000000000000001100001, which is ridiculously wasteful. The entire English alphabet can be represented by 6 bits,. So they came up with surrogates, a way to represent very large code points, without being wasteful. Let’s take a look at how the smiling emoji: 😀 is represented:

'\uD83D\uDE00'

This may seem like an odd way to encode characters, but if you look at the binary representation it might look more clear:

1101100000111101 1101111000000000

## So how to deal with them?

ES6 (a new JS version), provides many solutions for better handling these characters with high code-points

### Making them

Before, you’d have figure out what the surrogates are in order to write a multi-byte char.

var emoji = '\uD83D\uDE00';

Now, with the \u{...} syntax, you can simply enter the unicode code-point of the character without having to figure out the surrogates

let emoji = '\u{1F603}';

### Iterating / Splitting them

Very often when manipulating strings, you need to reference a specific character, or loop through the string. Problem is, if you were to do:

"😀"[0]

you’d only get the first-half of the surrogate. Additionally if I were to split it ordinarily:

c // -> [", ", ", "]

The output is weirdly printed because the individual surrogates are being split and this results in a very improper UTF-16 string.

The solution is ES6’s “spread” operator. This essentially spreads an iterable (e.g. string, array) into the parent nest structure (confusing, I know), basically very similar (if not identical) to Ruby and Python’s splat. The syntax for the spread operator is: ...iterable but make sure you wrap it in another iterable to spread in. An example usage is: [1, ...[2, 3]] -> [1, 2, 3].

So how does this apply? Just use it on a string and ta-da

[..."🐶🐱🐹"] // -> ["🐶", "🐱", "🐹"]

Additionally, if you’d like to loop through the string:

for (let char of "🐶🐱🐹") {
console.log(char); // "🐶"
// "🐱"
// "🐹"
}

Warning: this only works on native implementations of ES6, using a transpiler like Babel, this will not work.

Don’t have ES6 (or can’t support it)? Well then you can use this magic bit of code:

"🐶🐱🐹".match(/([\uD800-\uDBFF][\uDC00-\uDFFF])|[.\n]/g) // -> ["🐶", "🐱", "🐹"]

Surrogate characters have their own reserved characters for starting and ending them, because of this, we can extract either match from the string:

• Match a start-surrogate, then an ending-surrogate ([\uD800-\uDBFF][\uDC00-\uDFFF])
• Match any single-byte character ([.\n])

The match function then takes these matches and puts them in an array

So, yay? You know those cool multi-racial emojis on your iPhone (skin tone modifiers)? Yeah, the thing that makes them the specific color has its own character/byte to specify (e.g. is represented as <emoji_surrogate><skin_tone_modifier>). You’ll need to handle that separately:

"👶🏽".match(/([\uD800-\uDBFF][\uDC00-\uDFFF])(\uD83C[\uDFFB-\uDFFF])?|[.\n]/g)
// -> ["👶🏽"]

The only difference between this and the other one is it has an optional: (\uD83C[\uDFFB-\uDFFF])?, which matches a skin-tone modifier character.

## Filtering

You might want to filter these high code-point characters, to avoid spam, save space, or other reasons. If you are really choosing to do this, you might just limit to printable ASCII:

str.replace(/[^\x20-\x7E]/g, "");

But if you want to remove unprintables, you’ll have to use a monster regex…