Split a string into characters (emoji-safe) in JavaScript
Intermediate · 3 min read
Breaking a word into its letters sounds like the simplest string job there is. You need it to count letters, shuffle them for a game, check each one, or reverse a word. Most tutorials reach for split(''), and for plain English text it works.
In this tutorial you will split a string into characters two ways, split('') and the spread syntax [...text], and then run both on 'a👍b'. Only one of them gives the right answer. By the end you will know why, and which one to use. You should know what a string and an array are.
How JavaScript stores text
Inside JavaScript, a string is a list of small pieces called code units. An ordinary letter like a takes one code unit. Many emoji, like 👍, are too big for one and take two. Those two halves are called a surrogate pair. On their own, each half is meaningless and can't be displayed.
The length of a string counts code units, not the characters you see:
console.log('a'.length); // 1
console.log('👍'.length); // 2
Two ways to walk a string
split('') cuts between every code unit. The spread syntax [...text] walks the string one code point at a time. A code point is one whole Unicode character, so it keeps both halves of an emoji together. Array.from(text) walks the string the same way as spread.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
25 Split into characters, and why split(‘’) is wrong
fairBreak a string into its characters. Do it with split('') and with spread, then run both over 'a👍b' and see which one is telling the truth.
Stuck? Three hints, smallest first
- 1.
split(‘’)splits into UTF-16 code units, not characters. - 2. Spread and
Array.fromboth iterate code points, which keeps an emoji whole. - 3. An emoji is stored as a surrogate pair, so it is two code units and one code point.
Step 1: split a plain word
console.log('Lagos'.split('')); // [ 'L', 'a', 'g', 'o', 's' ]
console.log([...'Lagos']); // [ 'L', 'a', 'g', 'o', 's' ]
For plain letters both ways agree, because every letter is one code unit and one code point. This is why the split('') habit is so common: it passes every test written with ordinary words.
Step 2: add an emoji
const emoji = 'a👍b';
console.log(emoji.split('').length); // 4
console.log([...emoji].length); // 3
console.log([...emoji]); // [ 'a', '👍', 'b' ]
You can see three characters. split('') gives four pieces, because it cut the emoji into its two halves. Spread gives three, with the emoji whole.
Step 3: look at what split produced
const emoji = 'a👍b';
console.log(emoji.split('')[1] === '👍'); // false
console.log([...emoji][1] === '👍'); // true
console.log(emoji.length); // 4
The second piece from split('') is only the first half of the emoji, so it isn't equal to '👍'. Spread's second piece is the real emoji. emoji.length is 4, which tells you length is counting code units too.
Step 4: Array.from works the same way
console.log(Array.from('a👍b').length); // 3
Use whichever reads better to you. Array.from also takes a second argument, a function to run on each character, which is sometimes handy.
Step 5: when split('') looks safe
If you split and then join straight back in the same order, the halves end up next to each other again, so the text is restored:
const emoji = 'a👍b';
console.log(emoji.split('').join('') === emoji); // true
That is why the bug can hide for a long time.
Step 6: when it breaks
The moment you reorder the pieces, the halves get separated or swapped:
const emoji = 'a👍b';
const bySplit = emoji.split('').reverse().join('');
const bySpread = [...emoji].reverse().join('');
console.log(bySpread); // 'b👍a'
console.log(bySplit === bySpread); // false
The split version swapped the two halves of the emoji, and the result can't be displayed as a thumbs-up. Reversing, sorting, shuffling and slicing all have this problem. Spread keeps each emoji in one piece, so it survives.
The full solution
Here is the complete answer: both methods on a plain word, then both on 'a👍b', with checks for the lengths and the broken halves. Press Run and compare the two arrays printed for the emoji string.
const emoji = 'a👍b';
console.log("'Lagos'.split('') :", 'Lagos'.split(''));
console.log("[...'Lagos'] :", [...'Lagos']);
console.log('--- and now with an emoji ---');
console.log("emoji.split('') :", emoji.split(''), '<- four items, two of them broken halves');
console.log('[...emoji] :', [...emoji], '<- three items');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('for plain text both give the same characters', 'Lagos'.split(''), ['L', 'a', 'g', 'o', 's']);
test('and spreading agrees', [...'Lagos'], ['L', 'a', 'g', 'o', 's']);
test('the emoji string is three characters', [...emoji].length, 3);
test('but split MANGLES it into four pieces', emoji.split('').length, 4);
test('spreading keeps the emoji whole', [...emoji][1], '👍');
test('split does not', emoji.split('')[1] === '👍', false);
test('because length counts UTF-16 code units', emoji.length, 4);
test('Array.from behaves like spreading', Array.from(emoji).length, 3);
test('joining the split halves straight back does restore the text', emoji.split('').join(''), emoji);
test('but reordering them does not', emoji.split('').reverse().join('') === [...emoji].reverse().join(''), false);
split('') is safe only if you put the pieces back in the same order. The moment you reverse, sort, shuffle or slice them, a surrogate pair gets separated and you have produced text that no font can render.
Spread and Array.from both use the string iterator, which yields code points. That fixes emoji and astral characters. It does not fix combining marks — 'e' + U+0301 is still two code points for one visible letter — which is exercise 39.
Common mistakes
- Using
split('')on text people type. Names, messages and comments often include emoji. Use[...text]orArray.from(text). - Trusting
lengthas a character count.'👍'.lengthis 2. Count characters with[...text].length. - Thinking spread fixes everything. An accented letter written as a letter plus a separate accent mark is still two code points. That case is covered in the accents and emoji reversal exercise.
Try it yourself
- Write
charCount(text)that returns 3 for'a👍b'. - Take the first two characters of
'👍👍👍'safely, without cutting an emoji in half. - Sort the characters of
'b👍a'with spread andsort(), then join them back.