Cara menggunakan reverse string javascript recursion

Reversing a String is indeed one of the most common and needed operations in JavaScript. During the journey of any Software Developer's career, a very important and basic question for interviews is "How to Reverse a String in JavaScript"

There are a few ways to reverse a string in JavaScript. We can use loops, built-in functions, recursion and even regular expressions to solve the problem. In this post, I am going to show these approaches with examples. So, let's get started!!

🔶built-in Methods: split().reverse().join()

The very first way that I want to discuss is perhaps the most commonly used way, which is using the built-in methods. First of all, we need to split the string to an Array of Single Characters i.e.("s","t","r","i","n","g"), then reverse the characters and lastly join them again to create the reversed string.
Let's see an example first:

Cara menggunakan reverse string javascript recursion

In this example, basically three built-in methods are used. They are : String.prototype.split(), Array.prototype.reverse() & Array.prototype.join(). To understand it properly, I am explaining it elaborately.

🔸 String.prototype.split() method splits the String object into an Array of String by separating the string into sub strings. In this case, stringToReverse.split("") returns the output as:

['S', 'o', 'f', 't', 'w','a', 'r', 'e', ' ', 'D', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r']

🔸 After the string is separated as an array of string, the Array.prototype.reverse() does the main work which is reversing the single array elements in place. The first array element is now the last array element and vice-versa.
In our case, splitString.reverse() returns the output as:


const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
0

🔸 The Array.prototype.join() method finally rejoins all the single characters previously separated by the split() method to recompose the reversed string. In our example the final output is:


const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
2

Chaining these Methods

Well, these three methods can be chained to make our code compact and clean in the following way and the output will be the same.

Cara menggunakan reverse string javascript recursion

However,instead of using String.prototype.split(), we can do this work using


const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
4 also, which is a ES6 syntax. It works the same way as before.

Cara menggunakan reverse string javascript recursion

So, the spread operator is exactly doing the same work as split() does, it is splitting the string object into single characters.

🔶Using Decrementing For Loop

This is an easy and oldest approach of reversing a string in JavaScript but works pretty well everywhere.

Cara menggunakan reverse string javascript recursion

🔸 At first, newString created an empty string to host the new created string.
🔸 The starting point of the loop will be (str.length - 1) which corresponds to the last character of the string, "r". As long as i is greater than or equals zero, the loop will go on. We are decrementing i after each iteration.
🔸 The function then returns the reversed string.

We can also use the


const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
5 syntax introduced by JavaScript ES6 which is also very easy to use and decreases the chances of mistake while writing the conditions of the loop.

Cara menggunakan reverse string javascript recursion

Much cleaner than the previous for loop, isn't it?? But works really fine!

🔸 The "c" in the for loop condition is taking each of the letter of the string as a single character. For better understanding I have added two console.log() statement in the following picture and also you can see the output in the terminal.

Cara menggunakan reverse string javascript recursion

🔶The Recursive Approach: Recursion Method

Using the Recursion method is another very well-known approach to reverse a string in JavaScript. We need two methods to perform this recursive approach. One is the


const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
6 method and another is the

const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
7 method.
Let's see an example:

Cara menggunakan reverse string javascript recursion

🔸 String.prototype.substr() method returns a portion of the string, beginning at the specified index and extending for a given number of characters afterwards.
In our example, the part


const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
8 returns "ecursion".

🔸


const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
7 method returns the specified character from a string.
In our example, the part
const reverseString = (str) => str.split("").reduce((reversed, character) => character + reversed, "");

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR
0 returns "R".

🔸

const reverseString = (str) => str.split("").reduce((reversed, character) => character + reversed, "");

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR
1 firstly returns the portion of the string , starting at the index of the first character to include in the returned substring . Second part of the method hits the if condition and the most highly nested call returns immediately.
We need to remember that this method won’t have just one call but have several nested calls.

Nevertheless, this approach is not a best approach for reversing a string as the depth of the recursion is equal to the length of the string and in case of a very long string, it takes much more time than any other method and the size of the stack is a major concern here.

🔶 Using Array.prototype.reduce() Method

The

const reverseString = (str) => str.split("").reduce((reversed, character) => character + reversed, "");

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR
2 method executes a reducer callback function on each element of the array, passing in the return value from the calculation on the preceding element and returns a single value as the final result. The syntax can be written as:
const reverseString = (str) => str.split("").reduce((reversed, character) => character + reversed, "");

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR
3

Let's see an example of this.

function reverseString(str) {
  const arr = str.split("");
  const stringReversed = arr.reduce((reversed, character) => {
    return character + reversed;
  }, "");
  return stringReversed;
}

console.log(reverseString("Swarnali")); //ilanrawS

Enter fullscreen mode Exit fullscreen mode

🔸 The reverseString function takes a string str as parameter.
🔸 The first thing that we need to do is to split the string into single characters. We took an array arr to hold the values.
🔸 reduce() function takes two parameters, reversed and character. If we compare it with the basic syntax of reduce(), reversed is the previous value/accumulator and character is the current value. The function stringReversed returns the current value adding it with the previous value, which is actually reversing the whole array characters and joining them together in a reversed way.

This code block can be more compact if we use JavaScript ES6 syntax. 👇


const reverseString = (str) => {
  return str.split("").reduce((reversed, character) => character + reversed, "");
};

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR

Enter fullscreen mode Exit fullscreen mode

Making it a one-line code:

const reverseString = (str) => str.split("").reduce((reversed, character) => character + reversed, "");

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR

Enter fullscreen mode Exit fullscreen mode

🔶Using Regular Expressions (RegEx)

This is one of the rarest and trickiest approaches of reversing a string but developers who love to play with JavaScript Regular Expressions can definitely try this approach. Also, in any interview, if you can show this, that might be a plus point as it is such an approach that people generally don't use and they will know that you have mastered another skill that is Regular Expressions!
The following is an example of this approach:

let str = "My name is Swarnali Roy";
let regex = /.{1,1}/ig

let result = str.match(regex);
let reveresed = result.reverse().join("");

console.log(reveresed); //yoR ilanrawS si eman yM

Enter fullscreen mode Exit fullscreen mode

🔸The simplest quantifier in RegEx is a number in curly braces: {n}. A quantifier is appended to a character (or a character class, or a [...] set etc) and specifies how many we need.
In our example, {1,1} denotes we exactly need 1 character to be matched. If we write console.log(result), then we will get something like this:

const reverseString = (str) => str.split("").reduce((reversed, character) => character + reversed, "");

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR
4

🔸 The RegEx here is mainly doing the work of separating the string object into single characters of an array. After separating the reverse() and join() method is working exactly like it worked with

const reverseString = (str) => str.split("").reduce((reversed, character) => character + reversed, "");

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR
5 or
const reverseString = (str) => str.split("").reduce((reversed, character) => character + reversed, "");

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR
6 as I have shown above in the built-in approach.