Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTconst string = "Hello World";
const reversed = Array.from(string).reverse().join("");
console.log(reversed);
BASHdlroW olleH
Another way to do it is to split using a blank string:
JAVASCRIPTconst string = "Hello World";
const reversed = string.split("").reverse().join("");
console.log(reversed);
BASHdlroW olleH
Finally, you can use the spread operator to create the array:
JAVASCRIPTconst string = "Hello World";
const reversed = [...string].reverse().join("");
console.log(reversed);
BASHdlroW 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:
JAVASCRIPTconst string = "Hello World";
let reversed = "";
for (let i = string.length - 1; i >= 0; i--) {
reversed += string[i];
}
console.log(reversed);
BASHdlroW 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.
JAVASCRIPTconst 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);
BASHdlroW 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!
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Getting Started with Svelte
How to deploy a .NET app using Docker
Best Visual Studio Code Extensions for 2022
How to deploy a Deno app using Docker
Learn how to use v-model with a custom Vue component
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Handlebars.js
Using Push.js to Display Web Browser Notifications
Building a Real-Time Note-Taking App with Vue and Firebase
Setting Up Stylus CSS Preprocessor
