Emmanuel Akinfulubi

JavaScriptString

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:

  1. Turn the string into an array of characters.
  2. Reverse the array.
  3. 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

fair

Reverse 'lagos'. Then reverse 'ab๐Ÿ‘' with split('').reverse().join('') and check whether the emoji survived.

Stuck? Three hints, smallest first
  1. 1. Strings have no reverse, so go through an array.
  2. 2. split(โ€˜โ€™) splits into code units, which is where the emoji breaks.
  3. 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:

JavaScript

console.log('lagos'.split('')); // [ 'l', 'a', 'g', 'o', 's' ]

Step 2: reverse the array

Now the array can do what the string couldn't:

JavaScript

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:

JavaScript

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:

Step 4

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

JavaScript

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:

JavaScript

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.

Step 6

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.

The answer

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.

10 checks

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 have reverse, so you get TypeError: "lagos".reverse is not a function. Go through an array first.
  • Forgetting join(''). Without it you return an array, not a string. And join() 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

  1. Reverse each word in 'good morning' but keep the words in their places, so you get 'doog gninrom'. (Hint: split on spaces first.)
  2. Use your function to check whether 'level' is a palindrome, a word that reads the same backwards.
  3. Try reverseByCodePoint('cafe\u0301'), where the รฉ is written as an e plus a separate accent mark. Where does the accent end up?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.