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:
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:
const string = "Hello World";
const reversed = Array.from(string).reverse().join("");
console.log(reversed);
dlroW olleH
Another way to do it is to split using a blank string:
const string = "Hello World";
const reversed = string.split("").reverse().join("");
console.log(reversed);
dlroW olleH
Finally, you can use the spread operator to create the array:
const string = "Hello World";
const reversed = [...string].reverse().join("");
console.log(reversed);
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:
const string = "Hello World";
let reversed = "";
for (let i = string.length - 1; i >= 0; i--) {
reversed += string[i];
}
console.log(reversed);
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.
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);
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!