How do you reverse a string in place in JavaScript?



In this tutorial, we will learn to reverse a string in place in JavaScript. How to reverse a string is one of the most popular questions asked in the interview of freshers. It’s an easy task but the interviewer can be tricky and make the same question difficult for you. For example, what if the interviewer asks you to write a pseudo code to reverse a string in place without using the extra space? You should have an answer ready in your mind for this kind of tricky question.

There are lots of ways to reverse a string. As developers develop a new logic, they can build new algorithms.

In this tutorial, we will see some most popular algorithms and methods to reverse a string by creating custom functions and built-in methods.

Using the reverse() Method

For every essential operation, JavaScript contains built-in methods. And the same way, it includes the reverse() method to reverse the array. In our case, we will convert a string to the character array and reverse it and join it again to make the string.

As we are using the built-in reverse method, it is an optimized method because every library function is created in such a way that it optimizes the better time complexity and space complexity.

Algorithm

Users can follow the below algorithm to reverse strings using the reverse() method.

  • Step 1 − Convert the string to the array of characters using the spread operator. The spread operator is the three dots (...), which is used to clone any object or array.

  • Step 2 − Next, reverse the array of characters using the reverse() method.

  • Step 3 − Join the reversed character array using the join() method, and your reversed string is ready.

Syntax

Users can follow the syntax below to use the algorithm's methods.

let string = "TutorialsPoint";
let charArray = [ ...string ]; // convert string to char array
charArray.reverse( ); // reverse the array of character
string = charArray.join(''); // join array of character.

Example

The below example demonstrates the use of the above algorithm.

<!DOCTYPE html>
<html>
<body>
   <h2> Reverse the string in place in JavaScript. </h2>
   <p> After reversing the "TutorialsPoint" string using reverse() method: </p>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
      let string = "TutorialsPoint";
      let charArray = [...string];
      charArray.reverse();
      string = charArray.join('');
      output.innerHTML = string;
   </script>
</body>
</html>

In the above output, users can see that our string is reversed finally.

Creating the Custom Algorithm using for Loop

This approach will create an incrementing for loop to reverse a string. We will reverse a string in-place in this section. The in-place reverse means to reverse the string without using the extra space or new variable. In the above approach, we have created the array of char, which means we have used the extra space.

Algorithm

Users can follow the below algorithm to reverse a string using the for a loop.

  • Step 1 − Iterate through the string from start to end of the string. We can find the endpoint of the string using the string length.

  • Step 2 − Start to append every character of the string in the front of the new string.

  • Step 3 − Continue step 3 till the end point of the string, and you will get the reversed string.

Users can follow the syntax below to reverse a string using the loop.

Example

In the below example, we have used the reverseString variable to store the reverse string and using the for loop we are making the string reverse.

<html>
<body>
   <h2> Reverse the string in place in JavaScript. </h2>
   <h4> After reversing the "welcome to TutorialsPoint" string using for loop algortim. </h4>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
      let string = "welcome to TutorialsPoint";
      let l = string.length; // finding the length of the string
      let reverseString = '';
      for (let i = 0; i < l; i++) {
         reverseString = string[i] + reverseString;
      }
      output.innerHTML = reverseString;
   </script>
</body>
</html>

Creating a Recursive Function to Reverse a String

This section will teach the recursive approach to reverse a string. We will not use any extra variables in this approach like the above approach, but when we make a recursive call, it stores all function calls and stack traces, which take more space than the single variable.

Algorithm

Follow the below algorithm to reverse a string recursively.

  • Step 1 − If the string is empty, return ‘ ’ which is an empty string.

  • Step 2 − If the string is not empty, append the first character at last and make a recursive function call sub-string starting from the first character to the end of the string.

  • Step 3 − Return the returned value from the recursive call of sub-string by appending first character of string at last.

Users can follow the below syntax to implement above algorithm.

Example

In the below example, we have implemented the recursive approach to reverse a string.

<html>
<body>
   <h2> Reverse the string in place in JavaScript.</h2>
   <h4> After reversing the "Hello world!" string using recuersive algortim. </h4>
   <div id="output"> </div>
   <script>
      let output = document.getElementById("output");
      function reverse(string) {
         if (string === "") {
            return "";
         } else {
         return reverse(string.substr(1)) + string[0];
         }
      }
      let result = reverse("Hello world!");
      output.innerHTML = result;
   </script>
</body>
</html>

Conclusion

In this tutorial, we have learned three different approaches to reversing a string. The first approach is the easiest and requires two lines of code as we use the built-in reverse method. The second approach is the best as it takes the lowest memory. The third approach is not so good as it will take more time and space.


Advertisements