Loading...

Reverse a string in JavaScript

Reverse a string in JavaScript

One of the most common JavaScript interview questions is asking how to reverse a string. This would test your understanding of programming logic and also help you develop your concepts by learning how to solve one problem in various ways.

There are many ways to reverse a string. Here are some of them:

Approach 1- Reverse a String With a Decrementing For Loop

function ReverseString(str) { // <em>Check input</em> if(!str || str.length < 2 || typeof str!== 'string') { return 'Not valid'; } // <em>Take empty array revArray</em> const revArray = []; const length = str.length - 1; // <em>Looping from the end</em> for(let i = length; i >= 0; i--) { revArray.push(str[i]); } // <em>Joining the array elements</em> return revArray.join(''); } ReverseString('codedamn'); //Output- nmadedoc
Code language: JavaScript (javascript)

Here we first check whether the input is a string or if its length is one or zero in which case, it cannot be reversed. Next, we initialize an empty array and traverse it backward in a for loop pushing every individual element in each iteration starting from the end and joining them using the join() function.

Approach 2 – Using spread operator

const ReverseString = str => [...str].reverse().join(''); ReverseString("codedamn") //Output- nmadedoc
Code language: JavaScript (javascript)

Here the spread operator is used to convert string to an array of characters(codedamn={c,o,d,e,d,a,m,n}. Then reverse() function is used to make a reverse array of characters concatenated using the join() function.

The spread operator allows an iterable to expand in places where 0+ arguments are expected.

Spread operator syntax

var variablename1 = [...value];
Code language: JavaScript (javascript)

Approach 3 – Using reduce() function for reverse

Use the spread operator to convert the string into an array of characters. Use reduce() function in JavaScript to make a reverse string from an array by concatenating the string in the forward direction.

// <em>Function to reverse the string</em> function ReverseString(str) { // <em>Returning reverse string</em> return [...str].reduce((x, y) =>y.concat(x)); } console.log(ReverseString("codedamn")) //Output- nmadedoc
Code language: JavaScript (javascript)

Approach 4 – Using inbuilt function

Use the inbuilt function split() in JavaScript to split a string into an array of characters i.e. [ ‘c’, ‘o’, ‘d’, ‘e’, ‘d’, ‘a’, ‘m’, ‘n’,]. Use the reverse() function in JavaScript to reverse the array of characters i.e.[ ‘n’, ‘m’, ‘a’, ‘d’, ‘e’, ‘d’, ‘o’, ‘c’, ]. Use the join() function in JavaScript to concatenate the elements of an array into a string.

// <em>Function to reverse string</em> function ReverseString(str) { return str.split('').reverse().join('') } //<em> Function call</em> ReverseString("codedamn"); //Output- nmadedoc
Code language: JavaScript (javascript)

Approach 5 – Reversing using recursion

function reverseString(str) { if (str === "") return ""; else return reverseString(str.substr(1)) + str.charAt(0); } reverseString("bat");
Code language: JavaScript (javascript)

Here we first check whether the string is empty or not. If the condition satisfies then we call the function recursively with the substring from index 1 to the end as the parameter and add the first element to it.

Example- First Part of the recursion method
You need to remember that you won’t have just one call, you’ll have several nested calls.

Each call:str==”?”reverseString(str.substr(1)) +str.charAt(0)
1st call – reverseString(“bat”)reverseString(“at”) +str.charAt(b)
2nd call – reverseString(“at”)reverseString(“t”) +str.charAt(a)
3rd call – reverseString(“t”)reverseString(“”) +str.charAt(t)

The second part of the recursion method
The method hits the if condition and the most highly nested call returns immediately.

3rd call will return reverseString(“”) +“t”=“t”
2nd call will return reverseString(“t”) +“a”=“t” + “a”
1st call will return reverseString(“at”) +“b”=“t” + “a” +”b”

The depth of the recursion is equal to the length of the String. This solution is not the best one and will be really slow if the String is very long and the stack size is of major concern.

Approach 6 – Using two pointers

function revStr(str) { let arr = new Array(str.length) let left = 0 let right = str.length - 1 while (left <= right) { arr[left] = str[right] arr[right] = str[left] left++ right-- } return arr.join("") }
Code language: JavaScript (javascript)

We start by creating an array of empty spaces. The number of empty spaces is equal to the length of the string. The reason we do this is so the array can be built-up from both the front and end.

We then define two pointers: left and right. The left pointer begins pointing with the first character of the string and the right pointer points at the last character.

In the while loop, we are making the left side of the array equal to the rightmost characters in the string, and the right side of the array equal to the leftmost characters in the string. When the pointers meet in the middle, the array has been built and we can then break out of the loop and return the joined array.

The advantage of using pointers over a for loop is that we can build the array from both sides, meaning the number of loops is cut in half. The disadvantage is that we have to store an extra variable in memory (right) but this is no big deal.

Conclusion

These are some ways to reverse a String in JavaScript. It is always better to know more than one approach to a simple problem. Hope you learned something new from this article.

Sharing is caring

Did you like what Krishnaditya Biswas wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far