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:
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.
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.
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.
๐ธ 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.
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.
๐ถ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:
๐ธ 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
๐ธ 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
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
๐ถ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
๐ธ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.
Top comments (25)
After long time you published blog,
The blog you write is in well formated wayโจ.
Thanks ๐
Thank you so much, keep following and supporting โบ๏ธ โบ๏ธ
Hey can I suggest you one thing!
Yes definitely you can..
Can you add snippet of code in such format into your blog.
dev-to-uploads.s3.amazonaws.com/up...
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.
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
You can make your own snippet using "carbon" snippet creator.
carbon.now.sh/
Oh thanks a lot! I'll keep this on my mind. :D
โค๏ธ
Oh yeah, its another method which I didn't mention, I can add it now. Thank you for reminding โบ๏ธ
Lovely article Swarnali. I have another approach for you to consider:
const reverseString = ([...str]) => str.reverse().join('');
console.log(reverseString('abcdefg')); // 'gfedcba' on console.
This is another good approach, I didn't know about this one before. Thank you so much!!
The regex can be simpler (a period is already a single character, and case sensitivity does not affect it):
Thank you for the suggestion. This is a better one
thank you! but emoji?
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
sorry. my question is how to reverse a strings include emoji ? thank you
Oh okay.. I'll try to upload that solution ASAP. โบ๏ธ
Can you instrument the algorithms? Which is fastest, slowest?
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
Thank you!
Great content. But most of the above methods will fail if you are using UTF-16 character.
Any SEO services package must include off site SEO services like backlink development, which help your website get external approval.