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
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

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.