How to Reverse Strings in JavaScript

How to Reverse Strings in JavaScript

Ferenc Almasi β€’ 2020 September 12 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

Want to reverse a string in JavaScript? You can do so with this one-liner:

Copied to clipboard! Playground
// Reverse strings with this one-liner
const reverse = str => str.split('').reverse().join('');

// This will return 'annA'
reverse('Anna');
reverse.js

This works by using built in functions, which follows three steps:

  • First, the passed string is split into idividual charachters. This results in an array
  • The elements of the array is reversed, so the last item becomes the first one, and so on
  • The elements of the array are joined together with an empty string, rebuilding the original string in reverse order

But what happens if you try this solution with emojis?

Copied to clipboard! Playground
// Using the reverse function on emojis
reverse('πŸ‘ΆπŸ‘¨πŸ‘΄');

// This will result in:
"οΏ½πŸ‘¨πŸ‘΄οΏ½"
emoji.js

This is because emojis are multibyte characters, meaning they are made up of multiple bytes.

Copied to clipboard! Playground
// If you convert "s" into a byte, you'll get:
73

// If you convert "πŸ‘¨" into a byte, you'll get:
f0 9f 91 a8
bytes.js

The solution works fine for UTF-8, but not for UTF-16 or UTF-32, which uses different numbers of bytes to represent a character. These multibyte characters cannot be reversed like a UTF-8 string. Instead, you need to split them up, like they were an array:

Copied to clipboard! Playground
// Reverse strings with this one-liner
const reverse = str => [...str].reverse().join('');

// This will now return the expected output 'πŸ‘ΆπŸ‘¨πŸ‘΄'
reverse('πŸ‘΄πŸ‘¨πŸ‘Ά');
reverse.js
How to Reverse Strings in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.