Loading...

How to reverse a string in JavaScript?

How to reverse a string in JavaScript?

Everyone tries to be straightforward but why not think in a reverse manner and think from a different perspective? Yes, so reversing a string is nothing simply swapping the last element of the string to the first element and so on. It has various use cases and practical usage in various situations.

IntroductionšŸ”Š

Reversing a string is a common problem irrespective of the programming language. It has many use cases like checking a palindrome, encoding purposes, frequently asked interview questions, etc.


Methods to reverse a string in JSāž°

  • Using Loop
  • Using built-in functions
  • Using recursion

Reverse a string using LoopšŸ”

Here we use two variables one which contains the string and the other which will contain the reversed string. The logic here is that we will run the loop from reverse and concatenate the elements directly into the reverse string. The code base implementation is below:

// Using Loop var str = "Codedamn"; var revString = ""; for (var i = str.length() - 1; i >= 0; i++) { revString += str(i); } console.log(revstring);
Code language: JavaScript (javascript)

Here variable str is the initial string, variable revString which is initially empty and will contain the reversed string updated every time the loop runs.

The traversing of the string starts from the end and proceeds until the first letter. While traversing each element we concatenate it to the variable revString.

Reverse a string using built-in functionsāš™ļø

A oneliner that does the magic to reverse the string, but lots of computations go in the back.

// Using built-in functions var string = "Codedamn"; console.log(string.split("").reverse().join("")); // Step - 1: ["C", "o", "d", "e", "d", "a", "m", "n"] // Step - 2: ["n", "m", "a", "d", "e", "d", "o", "C"] // Step - 3: "nmadedoC"
Code language: JavaScript (javascript)

Initially, we store the string that needs to be reversed in the variable string. Then we perform three operations namely:

  1. Split: Convert the given string to an array with each letter equivalent to an array element using split() function.
  2. Reverse: We will reverse the elements of the array using the reverse() function.
  3. Join: Finally, we will convert it back to a string and display it.

Though it seems simple and elegant it takes some more time as we need to perform three different functions.

Reverse a string using recursionšŸ”‚

Recursion is a condition where a function calls itself. You can understand more about recursion by watching this youtube video. Using this technique we will reverse the string.

// Using recursion function revStr(string) { if (string === "") return ""; else return revStr(string.substr(1)) + string.charAt(0); } revStr("Codedamn"); // revStr("Codedamn") ===> revStr("odedamn") + "C" // revStr("odedamn") ===> return revStr("dedamn") + "o" // revStr("dedamn") ===> return revStr("edamn") + "d" // revStr("edamn") ===> return revStr("damn") + "e" // revStr("damn") ===> return revStr("amn") + "d" // revStr("amn") ===> return revStr("mn") + "a" // revStr("mn") ===> return revStr("n") + "m" // revStr("n") ===> return revStr("") + "n"
Code language: JavaScript (javascript)

In the first line, we define the function revStr that accepts string as a parameter. Then we use a conditional statement to check if the variable string is empty. If itā€™s true then we return an empty string "" and exit the function. If itā€™s false then we call the function again by concatenating the substring and the first character.

Initially, we pass the string Codedamn and we will return revStr("odedamn") and C. Then again we call the revStr("odedamn") function which is a recursive call. This occurs until the base case is satisfied. Here the base case is str === "" when attained at this case then we will return the values captured at each recursive call for string.charAt(0). The values are returned in reverse order which is the reversed string.


ConclusionšŸ”š

  1. We have learned to reverse a string with different use cases of where they are implemented.
  2. Three different methods of how we can reverse a string.
  3. Individual implementation and explanation to each of them.

You can learn more about the basics of Javascript in the course Learn JavaScript Basics.

Sharing is caring

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

0/10000

No comments so far