Reverse A String In JavaScript

Introduction

"How to reverse a string in JavaScript?" is one of the most frequently asked interview questions, especially if you're a fresher or have minimal experience. Potentially there could be dozens of ways we could reverse a string. However, in this article, we'll learn three different methods to reverse a string in JavaScript.

The string for this article will be "hello world!". However, these methods work with any strings you wish to reverse.

const str = 'hello world!';    
// Expected Output: !dlrow olleh

Reverse a string using Split, Reverse, Join

In this first method, we'll use JavaScript's built-in split, reverse, and join methods to reverse the string.

const str = 'hello world!';  
  
// step 1:  
const strChunks = str.split("");  
console.log(strChunks); // Output: ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]  
  
// step 2:  
const strChunksReverse = strChunks.reverse();  
console.log(strChunksReverse); // Output: ["!", "d", "l", "r", "o", "w", " ", "o", "l", "l", "e", "h"]  
  
// step 3:  
const strReverse = strChunksReverse.join("");  
console.log(strReverse); // Output: !dlrow olleh  

As you can see in the above code, in the first step, we're splitting the string "hello world" into an array using the split method, with each element representing a single character of the string. The parameter passed to the split method is an empty string with no spaces. In the next step, we're reversing that array using JavaScript's native reverse method, which reverses the elements in the array. And in the final step, we're joining the array elements, i.e., string characters, using the join method.

Instead of writing each operation in a separate statement, we could chain the methods and perform all the operations in a single line.

const str = 'hello world!';  
const strReverse = str.split('').reverse().join('');  
console.log(strReverse); // Output: !dlrow olleh  

The above code snippet will produce the same output as the previous code block.

Reverse a string using for loop

Next, we'll be using a simple for loop to reverse a string. 

const str = "hello world!";    
let strReverse = "";    
    
for (let i = str.length - 1; i >= 0; i--) {    
    strReverse = strReverse + str[i];    
}    
    
console.log(strReverse);    
// Output: !dlrow olleh   

As you can see in the above code snippet, we're creating a variable strReverse that contains an empty string (with no spaces in it). The next thing we're doing is we're looping over the string that needs to be reversed using the for loop. The initial value of I in the loop is the str.length - 1 i.e. the index of the exclamation mark character. After each interation we're decrementing the value of i. The loop will continue until it reaches the string's first character, i.e., h, from the word hello. In each iteration, we're concatenating the character to the strReverse variable.

Reverse a string using Recursion

And last but not least, we'll see how to reverse a string using the recursion. Recursion is simply a process where a function calls itself directly or indirectly.

const message = "hello world!";  

function reverse(value) {    
  return value === '' ? '' : reverse(value.slice(1)) + value.charAt(0);    
};  
  
console.log(reverse(message));  
// Output: !dlrow olleh  

The first thing the above function does is to check if string passed to it as parameter is empty. If yes, it'll simply return an empty string. If the condition is false, it'll simply call itself and pass the string value again, but this time, it'll remove the first character and pass the rest of the string, appending the first character at the end of the return statement.

Let's understand this using an easier example. Let's say we're passing string 'abc' to the function:

console.log(reverse('abc'));  // Output: cba   

The above code will call the reverse function four times. First time we're manually calling it, and 3 times, it'll call itself with recursion.

  • First time: reverse('abc') which will return reverse('bc') + 'a'
  • Second time: reverse('bc') which will return reverse('c') + 'ba'
  • Third time : reverse('c') which will return reverse reverse('') + 'cba'
  • Fourth time: reverse('') which will return an empty string terminating the recursion process.

And that's it! 

I hope you enjoyed this article. If you've any queries or feedback, please drop a message in the comment section.


Similar Articles