How To Reverse A String In JavaScript - Mastering JS

Tutorials / Fundamentals / How to Reverse a String in JavaScript Sep 21, 2021

To reverse a string, you can transform the string into an array and then use JavaScript arrays' built-in reverse() method.

Array.from('help').reverse().join(''); // pleh

or

let str = 'help'; [...str].reverse().join(''); // pleh

You can also use str.split('').reverse().join(''), but we recommend using Array.from() or the spread operator. The split() method does not handle UTF-16 characters, like emojis.

Reverse a String Without Built-in Methods

Reversing a string without any built-in methods is a common interview question. You can use a for loop to iterate through the string in reverse as shown below.

let str = 'hello world'; let reversed = ''; for(let i = str.length - 1; i >= 0; i--) { result += str[i]; } return result;

Using Recursion

Another approach for reversing a string is using recursion. The idea is that you can break down the problem of reversing a string into two steps:

  1. Swap the first and last characters of the string
  2. Reverse everything except for the first and last characters
function reverseString(str = '') { if (str.length <= 1) { return str; } const firstChar = str.charAt(0); const lastChar = str.charAt(str.length - 1); return lastChar + reverse(str.slice(1, str.length -1)) + firstChar; } Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

  • The `setTimeout()` Function in JavaScript
  • JavaScript Array flatMap()
  • How to Get Distinct Values in a JavaScript Array
  • Check if a Date is Valid in JavaScript
  • Encode base64 in JavaScript
  • Check if URL Contains a String
  • JavaScript Add Month to Date

Tag » How To Reverse A String Javascript