How to reverse a string in JavaScript
As a student, or if you are just beginning your journey to learn how to code - reversing a string is a typical problem that you may be asked to solve. In this short guide, we will present a solution in plain JavaScript that will solve our problem.
This article has a part 2 on how to check if a word is a palindrome.
Solution
Let's get down to business. We will create a function that will take a string as an argument and then loop through each character and pick them one by one in a reversed order.
const reverse = (str) => { if (!str) { return ""; } let reveresed = ""; let index = str.length - 1; while (index >= 0) { reveresed += str[index]; index--; } return reveresed; };
Notes
- We are first checking that our string is not falsy (empty or null/undefined)
- We are creating our index counter that will start on the last character of the string, and then in the while loop we will apply the characters one by one to our reversed string, and decreasing the counter by one for every iteration until we hit 0.
Test our function
Let's test our function, first with a string and then we will take the reversed version and reverse it again to get our original value back
console.log(reverse("This will be reversed")); // desrever eb lliw sihT console.log(reverse("desrever eb lliw sihT")); // This will be reversed
And that's it!
Outro
In this short tutorial, we showed how we can reverse a string in JavaScript in plain code. I hope you found this helpful, and thanks for reading.
All the best,