Reverse a String in JavaScript
Tags: javascript, career, beginners, tutorial
Published: 2021-09-06 09:51:05

**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!! 

####:large_orange_diamond: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:

![split().reverse().join()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ktboawa1l3ninfea6af.png)

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.

:small_orange_diamond: `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'] `

:small_orange_diamond: 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:

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

:small_orange_diamond: 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: 

` repoleveD erawtfoS `

####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.

![Chaining methods together](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a3t77prsy6t8sa0iyf07.jpg)

However,instead of using `String.prototype.split()`, we can do this work using `Spread Operator [...]` also, which is a *ES6 syntax*. It works the same way as before.

![Using spread operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ch7nqwd1ncgydw36xtde.jpg)

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

####:large_orange_diamond:Using Decrementing For Loop

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

![For Loop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6pkihhjh9z9eu4cab6v.png)

:small_orange_diamond: At first, *newString* created an *empty string* to host the *new created string*.
:small_orange_diamond: 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.
:small_orange_diamond: The function then *returns* the *reversed string*.

We can also use the `for loop` 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.

![For loop ES6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/45ok7anh1sghu0uvbo4u.jpg)

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

:small_orange_diamond: 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.

![For of loop with console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4svsioj0uxutsrxnifss.jpg)

####:large_orange_diamond: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 `String.prototype.substr()` method and another is the `String.prototype.charAt()` method.
Let's see an *example*:

![Recursive Approach](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b7hi82myi68ha9gsv99x.jpg)

:small_orange_diamond: *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 `str.substr(1)` returns *"ecursion"*.

:small_orange_diamond: `String.prototype.charAt()` method returns the *specified character* from a string.
In our example, the part `str.charAt(0)` returns *"R"*.

:small_orange_diamond: `reverseString(str.substr(1)) + str.charAt(0)` 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. 

####:large_orange_diamond: Using Array.prototype.reduce() Method

The `Array.prototype.reduce()` 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: 
` reduce((previousValue, currentValue) => { ... } ) `

Let's see an *example* of this.

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

console.log(reverseString("Swarnali")); //ilanrawS
```
:small_orange_diamond: The *reverseString* function takes a string *str* as parameter. 
:small_orange_diamond: 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. 
:small_orange_diamond: 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. :point_down:

```js

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

console.log(reverseString("Roy is a Developer"));
//repoleveD a si yoR
```
Making it a one-line code:

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

console.log(reverseString("Roy is a developer"));
//repoleveD a si yoR
```
####:large_orange_diamond: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:

```js
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
```

:small_orange_diamond: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:
`['M', 'y', ' ', 'n', 'a','m', 'e', ' ', 'i', 's', ' ', 'S', 'w', 'a', 'r', 'n', 'a', 'l', 'i', ' ','R', 'o', 'y']`

:small_orange_diamond: 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 `split()` or `spread operator` as I have shown above in the *built-in approach*.

######I hope the readers understood the tutorial and it can help you in your interviews as well. Queries are always welcomed in the discussion section.