JavaScript - How to Reverse a String (3 ways)
In this tutorial, we are going to learn three different ways to reverse a string in JavaScript by using the reverse()
method, reduce()
method, while loop.
Reversing the string
To reverse a string in JavaScript, we can use the combination of split()
, reverse()
and join('')
methods.
Here is an example:
const str = "hello"
const reverse = str.split('').reverse().join('');
console.log(reverse); // "olleh"
In the above example, we used the split()
method to split the given string into an array of individual characters then chain it to reverse()
, join()
methods.
split(): The split()
splits the given string into an array of individual characters.
reverse(): The reverse()
method reverses the array.
join(): The join() method joins the array of individual characters into a string.
Using reduce() method
To reverse a string , we can use the reduce()
method in JavaScript.
const str = "hello"
const reverse = [...str].reduce((prev,next) => next+prev);
console.log(reverse); // "olleh"
In the example above, first we unpack the string into a array of individual characters using spread operator (…) then we reverses the string using the reduce()
method.
Using while loop
function reverseString(str){
const arr = [...str];
let reverse= "";
while(arr.length){
// joining the reversed string
reverse = reverse + arr.pop();
}
return reverse;
}
console.log(reverseString('hi')); // ih
I mostly like the Second way to reverse a string using reduce()
method.
Happy coding…