Reverse a string in JavaScript
Intermediate ยท 3 min read
Reversing a string is one of the most common beginner exercises, and a favorite interview question: 'lagos' should become 'sogal'. It is also a great way to learn three methods you will use all the time: split, reverse and join.
There is a twist most tutorials skip. The usual one-line answer breaks emoji. By the end of this tutorial you will know why, and you will have a version that works for any text.
Why strings have no reverse()
Arrays have a reverse() method. Strings don't. A string in JavaScript can't be changed once it is made, so there is nothing to flip in place. Instead, the plan is:
- Turn the string into an array of characters.
- Reverse the array.
- Join the characters back into a string.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
38 Reverse a string
fairReverse 'lagos'. Then reverse 'ab๐' with split('').reverse().join('') and check whether the emoji survived.
Stuck? Three hints, smallest first
- 1. Strings have no
reverse, so go through an array. - 2.
split(โโ)splits into code units, which is where the emoji breaks. - 3. Spreading iterates code points, so it keeps a surrogate pair together.
Step 1: split the string into an array
split(''), with an empty string between the brackets, cuts the text between every character:
console.log('lagos'.split('')); // [ 'l', 'a', 'g', 'o', 's' ]
Step 2: reverse the array
Now the array can do what the string couldn't:
console.log(['l', 'a', 'g', 'o', 's'].reverse()); // [ 's', 'o', 'g', 'a', 'l' ]
Step 3: join it back together
join('') glues the pieces back together with nothing between them:
console.log(['s', 'o', 'g', 'a', 'l'].join('')); // 'sogal'
Step 4: put it all in one function
Each method hands back something the next one can use, so you can chain all three on one line:
const reverse = (text) => text.split('').reverse().join('');
console.log(reverse('lagos')); // 'sogal'
This is the answer you will see almost everywhere. Now for the twist.
Step 5: try it on an emoji
console.log(reverse('ab๐')); // not '๐ba': the thumbs-up comes out broken
Inside JavaScript, a string is stored as small pieces called code units. An ordinary letter takes one. Many emoji, like ๐, take two. split('') cuts between code units, so it cuts the emoji in half, and reverse() then puts the two halves in the wrong order. What comes out can't be displayed.
You can see the two halves for yourself:
console.log('๐'.length); // 2
console.log('๐'.split('').length); // 2 pieces, not 1 emoji
Step 6: split by real characters
The spread syntax, [...text], walks through a string one real character at a time. It keeps both halves of an emoji together.
const reverseByCodePoint = (text) => [...text].reverse().join('');
console.log(reverseByCodePoint('lagos')); // 'sogal'
console.log(reverseByCodePoint('ab๐')); // '๐ba'
Same plan as before, with one change: [...text] instead of text.split('').
The full solution
Here are both versions side by side. Press Run and compare the two results for 'ab๐'. The checks underneath prove each claim, including that the split version really does break.
const reverse = (text) => text.split('').reverse().join('');
const reverseByCodePoint = (text) => [...text].reverse().join('');
console.log("reverse('lagos') :", reverse('lagos'));
console.log("reverse('ab๐') :", reverse('ab๐'), '<- the emoji is now two stray halves');
console.log("reverseByCodePoint('ab๐') :", reverseByCodePoint('ab๐'));
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('a plain word reverses', reverse('lagos'), 'sogal');
test('an empty string reverses to itself', reverse(''), '');
test('and so does a single character', reverse('a'), 'a');
test('reversing twice returns the original', reverse(reverse('lagos')), 'lagos');
test('spaces move like anything else', reverse('a b'), 'b a');
test('for plain text both versions agree', reverseByCodePoint('lagos'), 'sogal');
test('but split BREAKS the emoji, because it cuts code units apart', reverse('ab๐') === '๐ba', false);
test('spreading keeps it whole', reverseByCodePoint('ab๐'), '๐ba');
test('the broken result still has the right number of code units', reverse('ab๐').length, 4);
test('it is the ORDER of the two halves that is wrong', reverse('ab๐').slice(0, 2) === '๐', false);
This is the interview question that everybody knows and almost everybody answers with the broken version. split('').reverse().join('') is fine for ASCII and produces unrenderable text for anything above U+FFFF, because the two halves of a surrogate pair come out in the wrong order.
[...text] fixes emoji. It does not fix combining marks, where the accent would end up attached to the wrong letter, and it does not fix ZWJ sequences. Exercise 39 goes after those.
Common mistakes
- Calling
'lagos'.reverse(). Strings don't havereverse, so you getTypeError: "lagos".reverse is not a function. Go through an array first. - Forgetting
join(''). Without it you return an array, not a string. Andjoin()with nothing in the brackets puts commas between the letters:'s,o,g,a,l'. - Using
split('')on text people type. Names, chat messages and comments often contain emoji. Use[...text]there.
Try it yourself
- Reverse each word in
'good morning'but keep the words in their places, so you get'doog gninrom'. (Hint: split on spaces first.) - Use your function to check whether
'level'is a palindrome, a word that reads the same backwards. - Try
reverseByCodePoint('cafe\u0301'), where the รฉ is written as an e plus a separate accent mark. Where does the accent end up?