In JavaScript, we don’t have a direct way to reverse a string. In other words, there is no in-built function that can revere a string in one go.
Then the question arises, how do I reverse a string in JavaScript?
String manipulation is one of the main tasks while learning programming. There are different ways to perform string reversal. Let’s see two ways to reverse a string in JS.
JavaScript String Reverse – The Middle Man’s Approach
Note– We can easily reverse an array using the reverse() function in JavaScript. But the problem here is that it can only reverse an array.
So what if? We can change the string to an array, use the reverse() function to reverse it and then change back the array to a String.
Wola!! we can get our job done. Yes, that’s correct. We can use different functions all together to achieve our string reversal task.
Let’s build a program in javascript and print the reverse string.
let string ='hello all';
string = string.split(''); // string to an array
string.reverse(); // reverse the array
string = string.join(''); // change back from array to string
//Display
console.log(string);
You can chain the above steps in a single line.
string = string.split('').reverse().join('');
In the above program, we have used the split() function to change the string to an array. There are more ways to convert string to array.
Using JavaScript Loop
Just like we can reverse an array using for loop, similarly, we can also use for loop to reverse a string.
Let’s build a program in javascript.
let string ='hello all';
let reverseString='';
for(let i=string.length-1;i>=0;i--){
reverseString+=string[i];
}
console.log(reverseString);
Likewise, as an alternative, you can also use a while loop too.
let string ='hello all';
let reverseString='';
let index=string.length-1;
while(index >=0){
reverseString+=string[index];
index--;
}
console.log(reverseString);
The idea here is really simple, the loop starts from the last index and runs until the very first. While we iterate, the value is stored in another variable and is concatenated. As a result, we get the reverse string.
Hope you loved the tutorial, let us know in the comments.
Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed