Reverse a string with accents and emoji in JavaScript
Advanced · 4 min read
Reversing a string is easy for plain English. Once you know that split('') breaks emoji, you switch to [...text] and think you are done. Then someone reverses the word café, written with a separate accent mark, and the accent lands on the wrong letter. Or they reverse a family emoji, and it falls apart into three people.
This is a harder exercise, but we will start from zero. You will learn the three levels of "character" in a JavaScript string, write a reverse that keeps accents on their letters, and then use the built-in Intl.Segmenter to handle emoji built from several pieces. You should know how [...text].reverse().join('') reverses a string.
Three levels of character
A string can be measured at three levels:
- Code units. The small pieces JavaScript stores.
lengthandsplit('')work at this level. Many emoji take two. - Code points. Whole Unicode characters.
[...text]works at this level, so an emoji stays in one piece. - Graphemes. What a reader would call one character. Some graphemes are built from several code points.
Combining marks and joiners
An accented letter like é can be written as one code point, or as a plain e followed by a combining mark: an accent code point (written \u0301) that attaches itself to the character before it. Both look the same on screen.
Some emoji are built the same way. A family emoji is a man, a woman and a girl, glued together by an invisible zero-width joiner (ZWJ, written \u200D). That is five code points that the screen shows as one picture.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
39 Reverse a string without breaking the accents
hardReverse 'cafe' written with a combining acute accent, so the accent stays on its own letter. Then try the same function on a family emoji.
Stuck? Three hints, smallest first
- 1. A combining mark is a separate code point that belongs to the character before it.
- 2. Group each base character with the marks that follow it, then reverse the groups.
- 3.
Intl.Segmenterwith grapheme granularity does this properly, including emoji sequences.
Step 1: a word with a combining accent
const decomposed = 'cafe\u0301';
console.log(decomposed.length); // 5
\u0301 inside a string is the combining acute accent. The word shows as café, but it is five code points: c, a, f, e and the accent.
Step 2: reverse it by code point
const decomposed = 'cafe\u0301';
const reverseCodePoints = (text) => [...text].reverse().join('');
console.log(reverseCodePoints(decomposed) === 'e\u0301fac'); // false
console.log(reverseCodePoints(decomposed) === '\u0301efac'); // true
The reader wants éfac: the e with its accent, then f, a, c. But reversing code points puts the accent first, before the e. A combining mark attaches to whatever comes before it, and now there is nothing before it, so the accent is left on its own.
Step 3: group each letter with its marks
The fix is to keep each character together with any marks that follow it, and reverse those groups. Two regex pieces help:
[\s\S]matches any one character at all (whitespace or not whitespace).\p{M}matches any Unicode mark, such as a combining accent. It needs theuflag, which makes the regex work with whole code points.
So [\s\S]\p{M}* means "one character, then any number of marks":
const graphemes = (text) => text.match(/[\s\S]\p{M}*/gu) || [];
console.log(graphemes('cafe\u0301').length); // 4
console.log(graphemes('lagos')); // [ 'l', 'a', 'g', 'o', 's' ]
Four groups: c, a, f and e with its accent. The || [] keeps an empty string from giving null.
Step 4: reverse the groups
const graphemes = (text) => text.match(/[\s\S]\p{M}*/gu) || [];
const reverseGraphemes = (text) => graphemes(text).reverse().join('');
console.log(reverseGraphemes('cafe\u0301') === 'e\u0301fac'); // true
console.log(reverseGraphemes('lagos')); // 'sogal'
console.log(reverseGraphemes('ab👍')); // '👍ba'
The accent now stays on its e. Plain words still work, and so do simple emoji, because the u flag means the regex never cuts an emoji in half.
Step 5: the family emoji breaks it
const graphemes = (text) => text.match(/[\s\S]\p{M}*/gu) || [];
const reverseGraphemes = (text) => graphemes(text).reverse().join('');
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}';
console.log(reverseGraphemes(family) === family); // false
console.log(/\p{M}/u.test('\u200D')); // false
A family emoji is one picture, so reversing it should leave it unchanged. It doesn't. The joiner isn't a combining mark, so our pattern treats each person and each joiner as separate groups and shuffles them.
Step 6: use Intl.Segmenter
You could keep adding rules, but the real rules for graphemes are long. JavaScript has them built in. Intl.Segmenter with granularity: 'grapheme' splits text into real graphemes:
const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
const reverseBySegmenter = (text) =>
[...segmenter.segment(text)].map((s) => s.segment).reverse().join('');
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}';
console.log(reverseBySegmenter(family) === family); // true
console.log(reverseBySegmenter('cafe\u0301') === 'e\u0301fac'); // true
segmenter.segment(text) gives a list of pieces. Each piece is an object, and its segment property holds the text. We take those texts, reverse them and join. The family stays whole, and the accented word comes out right too.
Step 7: a fallback
The answer on this page checks that Intl.Segmenter exists before using it, and falls back to the regex version if not:
const hasSegmenter = typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function';
console.log(hasSegmenter); // true
typeof is safe to use on things that might not exist, so this check never throws.
The full solution
Here is the complete answer: the code-point reverse, the grapheme regex, the Intl.Segmenter version with its fallback, and checks on the accented word and the family emoji. Press Run and compare the two family-emoji lines.
const reverseCodePoints = (text) => [...text].reverse().join('');
// Group every character with any combining marks that follow it. \p{M} is the
// Unicode "mark" category, and it needs the u flag.
const graphemes = (text) => text.match(/[\s\S]\p{M}*/gu) || [];
const reverseGraphemes = (text) => graphemes(text).reverse().join('');
// The real answer, where it is available.
const hasSegmenter = typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function';
const reverseBySegmenter = (text) =>
hasSegmenter
? [...new Intl.Segmenter('en', { granularity: 'grapheme' }).segment(text)]
.map((s) => s.segment)
.reverse()
.join('')
: reverseGraphemes(text);
const decomposed = 'cafe\u0301'; // cafe + combining acute
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}'; // man + ZWJ + woman + ZWJ + girl
console.log('code points :', decomposed.length, ' graphemes:', graphemes(decomposed).length);
console.log('by code point :', JSON.stringify(reverseCodePoints(decomposed)), '<- the accent moved');
console.log('by grapheme :', JSON.stringify(reverseGraphemes(decomposed)));
console.log('family emoji, marks version :', reverseGraphemes(family) === family);
console.log('family emoji, Segmenter :', reverseBySegmenter(family) === family);
Output
11 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 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the word is five code points but four graphemes', [decomposed.length, graphemes(decomposed).length], [5, 4]);
test('reversing by code point puts the accent on the wrong letter', reverseCodePoints(decomposed) === 'e\u0301fac', false);
test('grouping the mark with its letter fixes it', reverseGraphemes(decomposed), 'e\u0301fac');
test('a plain word is unaffected either way', [reverseCodePoints('lagos'), reverseGraphemes('lagos')], ['sogal', 'sogal']);
test('an astral character survives, since both work above code units', reverseGraphemes('ab👍'), '👍ba');
test('unlike split, which works in code units', 'ab👍'.split('').reverse().join('') === '👍ba', false);
test('reversing twice gets the graphemes back', reverseGraphemes(reverseGraphemes(decomposed)), decomposed);
test('a ZWJ emoji is beyond the mark-based version', reverseGraphemes(family) === family, false);
test('because a zero-width joiner is not a combining mark', /\p{M}/u.test('\u200D'), false);
test('Intl.Segmenter handles that one', hasSegmenter ? reverseBySegmenter(family) === family : true, true);
test('and it agrees with the mark version on the accented word', reverseBySegmenter(decomposed), reverseGraphemes(decomposed));
There are three levels of "character" and reversing exposes all of them. Code units break emoji. Code points break combining marks. Only grapheme clusters — what a reader would call a character — survive, and computing those properly needs the Unicode segmentation rules.
The \p{M}* trick handles the common case, which is Latin text with accents, and it fails on emoji built from joined sequences: a family is five code points held together by zero-width joiners, none of which is a mark. Intl.Segmenter knows the real rules and is in every current engine. Use it, and keep the regex version only as a fallback.
The honest conclusion is that reversing text is a display-layer operation that almost never needs doing. If it does, use Intl.Segmenter and do not write your own table.
Common mistakes
- Thinking
[...text]handles every character. It keeps emoji whole but separates combining marks from their letters. - Forgetting the
uflag. Without it,\p{M}doesn't mean "a mark", and the pattern doesn't work as intended. - Writing your own grapheme rules. Joined emoji and other cases need the full rules. Use
Intl.Segmenter.
Try it yourself
- Count the graphemes in
'cafe\u0301 👨👩👧'withIntl.Segmenter. (The space counts.) - Write
firstGrapheme(text)that returns the first visible character, even if it is a family emoji. - Reverse the words of a sentence, keeping each word's letters in order.