DEV Community

Cover image for Reverse a String in JavaScript
Swarnali Roy
Swarnali Roy

Posted on • Edited on

Reverse a String in JavaScript

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:

split().reverse().join()

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:

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

๐Ÿ”ธ 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

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

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.

For Loop

๐Ÿ”ธ 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 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

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.

For of loop with console

๐Ÿ”ถ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

๐Ÿ”ธ 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".

๐Ÿ”ธ String.prototype.charAt() method returns the specified character from a string.
In our example, the part str.charAt(0) returns "R".

๐Ÿ”ธ 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.

๐Ÿ”ถ 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.

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

๐Ÿ”ธ 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.

Top comments (25)

Collapse
 
star_trooper profile image
Atharva Shirdhankar

After long time you published blog,
The blog you write is in well formated wayโœจ.
Thanks ๐Ÿ‘

Collapse
 
swarnaliroy94 profile image
Swarnali Roy

Thank you so much, keep following and supporting โ˜บ๏ธ โ˜บ๏ธ

Collapse
 
star_trooper profile image
Atharva Shirdhankar

Hey can I suggest you one thing!

Thread Thread
 
swarnaliroy94 profile image
Swarnali Roy

Yes definitely you can..

Thread Thread
 
star_trooper profile image
Atharva Shirdhankar

Can you add snippet of code in such format into your blog.
dev-to-uploads.s3.amazonaws.com/up...

Thread Thread
 
star_trooper profile image
Atharva Shirdhankar

Even I have used in my blog the same snippet
dev.to/star_trooper/views-and-it-s...

And I have not written the blog in well formatted (text)way but yes due the snip format it is looking great.

Thread Thread
 
swarnaliroy94 profile image
Swarnali Roy

I haven't tried this ever. How can I get this format? Is it any app like vs code? Let me know. i will try

Thread Thread
 
star_trooper profile image
Atharva Shirdhankar

You can make your own snippet using "carbon" snippet creator.

carbon.now.sh/

Thread Thread
 
swarnaliroy94 profile image
Swarnali Roy

Oh thanks a lot! I'll keep this on my mind. :D

Collapse
 
rafipiccolo profile image
Raphael Piccolo

โค๏ธ

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited
const reverseStr = str => [...str].reduce((r,s)=>s+r)

reverseStr("Hello")  // olleH
Enter fullscreen mode Exit fullscreen mode
Collapse
 
swarnaliroy94 profile image
Swarnali Roy

Oh yeah, its another method which I didn't mention, I can add it now. Thank you for reminding โ˜บ๏ธ

Collapse
 
tracygjg profile image
Tracy Gilmore

Lovely article Swarnali. I have another approach for you to consider:
const reverseString = ([...str]) => str.reverse().join('');

console.log(reverseString('abcdefg')); // 'gfedcba' on console.

Collapse
 
swarnaliroy94 profile image
Swarnali Roy

This is another good approach, I didn't know about this one before. Thank you so much!!

Collapse
 
atnbueno profile image
Antonio Bueno • Edited

The regex can be simpler (a period is already a single character, and case sensitivity does not affect it):

let regex = /./g
Enter fullscreen mode Exit fullscreen mode
Collapse
 
swarnaliroy94 profile image
Swarnali Roy

Thank you for the suggestion. This is a better one

Collapse
 
linrstudio profile image
Linr

thank you! but emoji?

Collapse
 
swarnaliroy94 profile image
Swarnali Roy

Sorry, I didn't understand , do you want to know from where I'm getting the emojis?
webfx.com/tools/emoji-cheat-sheet/
this is the link from where you can copy the name of the emoji and paste it wherever you want in your blog

Collapse
 
linrstudio profile image
Linr

sorry. my question is how to reverse a strings include emoji ? thank you

Thread Thread
 
swarnaliroy94 profile image
Swarnali Roy

Oh okay.. I'll try to upload that solution ASAP. โ˜บ๏ธ

Collapse
 
dougaws profile image
Doug

Can you instrument the algorithms? Which is fastest, slowest?

Collapse
 
rafipiccolo profile image
Raphael Piccolo • Edited

Damn useless :) I'm not gonna need any of these functions in my whole life, but you have some interesting solutions here indeed. Nice post

Collapse
 
swarnaliroy94 profile image
Swarnali Roy

Thank you!

Collapse
 
krishrahul98 profile image
Rahul Krishna

Great content. But most of the above methods will fail if you are using UTF-16 character.

Collapse
 
robertbadams profile image
Robert Adams

Any SEO services package must include off site SEO services like backlink development, which help your website get external approval.