How to Reverse a String in JavaScript

Updated onbyAlan Morel
How to Reverse a String in JavaScript

Strings are a versatile data type in JavaScript because they can be used in many different forms.

A common operation performed on strings is reversing them, that is, reversing the order of the characters in the string.

In this post, we'll learn how you can reverse a string in JavaScript.

Using built-in methods

The easiest way to reverse a string is to use built-in methods like reverse and join.

Let's start out with an example string:

JAVASCRIPT
const string = "Hello World";

Now, we can reverse this string by converting it into an array of characters, reversing the array, then converting the array back into a string:

JAVASCRIPT
const string = "Hello World"; const reversed = Array.from(string).reverse().join(""); console.log(reversed);
BASH
dlroW olleH

Another way to do it is to split using a blank string:

JAVASCRIPT
const string = "Hello World"; const reversed = string.split("").reverse().join(""); console.log(reversed);
BASH
dlroW olleH

Finally, you can use the spread operator to create the array:

JAVASCRIPT
const string = "Hello World"; const reversed = [...string].reverse().join(""); console.log(reversed);
BASH
dlroW olleH

Using a for loop

Another way to reverse a string is to manually iterate over the string in reverse order and generating a new string:

JAVASCRIPT
const string = "Hello World"; let reversed = ""; for (let i = string.length - 1; i >= 0; i--) { reversed += string[i]; } console.log(reversed);
BASH
dlroW olleH

Using recursion

The final way to reverse a string is to use recursion.

This involves swapping the first and last characters, then reversing the middle part of the string, and then concatenating all three parts.

Eventually you get to the middle, which we just return since a string of length 1 is already reversed.

JAVASCRIPT
const string = "Hello World"; const reverse = string => { if (string.length <= 1) { return string; } const first = string.charAt(0); const last = string.charAt(string.length - 1); return last + reverse(string.slice(1, string.length -1)) + first; } const reversed = reverse(string); console.log(reversed);
BASH
dlroW olleH

Conclusion

In this post, we learned many different ways you can reverse a string in JavaScript.

Your options include using built-in methods, manually iterating over the string, or using recursion.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.