Site icon codippa

How to reverse a string in javascript with example

Reversing a string means creating a new string whose order of characters is the opposite. That is, last character is at first position, second last is at second and so on.
There are many different ways in which this can be done in javascript and this article will explain 4 different methods with example.


Method 1: Using for loop
This method reverses a string without using builtin reverse function and involves the following steps.

  1. Initialize an empty array to hold the characters of the string in reverse order.
  2. Iterate over the characters of the string from right to left using a for loop one by one.
  3. In every iteration, add the current character to the array created in Step 1 using its push function.
  4. After the for loop completes, the array created in Step 1 will hold the characters of the string in reverse order.
  5. Use join function to combine the elements of array into a string.

Javascript program based on these steps is written below.

Reversed string is <span id="result"></span>
<script>
   // declare string to reverse
   let str = "codippa";

   function reverseUsingIteration() {
      // create an empty array
      let reverseArr = [];
      // iterate over string in reverse order
      for(let i = str.length -1; i >=0; i--) {
         // push current character to the array
         reverseArr.push(str[i]);
      }
      // combine elements of array
      let reverseStr = reverseArr.join('');
      return reverseStr;
   }
   // get reversed string
   let reverseStr= reverseUsingIteration(str);
   // display reversed string
   document.getElementById("result").innerHTML=reverseStr;
</script>

Steps to run
Copy the above code. Save it in a file with a .html or .htm extension. Right click the file and open it in a browser.
Method 2: Using recursion
When a method repeatedly calls itself, it is called recursion and the method is called a recursive method. A string can be reversed in javascript using a recursive method also.
This recursive method should be based on the following pointers:

A terminating condition should be written at the beginning of a recursive method so that it should return at some point otherwise it will keep on calling itself forever.
Example,

Reversed string is <span id="result"></span>
<script>
   // declare string to reverse
   let str = "codippa";

   function reverseUsingRecursion(str) {
      // check if string is empty
      if(str == "") {
         // terminate recursion
         return "";
      }
      /* call itself with the first character removed
and added to the end */
      return reverseUsingRecursion(str.substr(1)) + str.charAt(0);
   }
   // get reversed string
   let reverseStr= reverseUsingRecursion(str);
   // display reversed string
   document.getElementById("result").innerHTML=reverseStr;
</script>

Above example defines a recursive function which calls itself with a string argument. It will keep on calling itself till the string argument is empty. This is the terminating condition of recursive method.

Notice that in every recursive call, the function removes first character from the string using substr function.
substr function accepts an integer which is the index of character in the string and returns a string with all the characters before this index(or index – 1) removed. That is,

// string with characters before index 2 removed
"codippa".substr(2) will return "dippa"   

// string with characters before index 4 removed
"Hello World".substr(4) will return "o World"

Remember that characters in a string are 0-based. That is, first character will have 0 index, second will have index 1 and so on.
To get a character at a particular index in a string, use its charAt method which accepts the index of the character in the string and returns it.
Thus, to get the first character, use charAt(0).
Recursive function defined in above example can be converted to a one-liner using ternary operator as below.

function reverseUsingRecursion(str) {
  /* return empty string if the argument is empty
    else call itself */
  return (str == "") ? "" : reverseUsingRecursion(str.substr(1))
+ str.charAt(0);
}

Method 3: Using inbuilt javascript functions
This method uses three builtin functions of javascript to reverse a string. These functions are
1. split: This method splits the string based on a separator and returns an array of substrings. This separator is supplied as the argument to this method.
Examples,

// split on a whitespace
"Hello World".split(" ");    // returns ["Hello", "World"]

// split on "n"
"learningisfun".split("n");   // returns ["lear", "i", "gisfu", ""]

Remember that the argument provided to split is not present in the array elements.
2. reverse: This function when called on an array reverses its elements. Example,

let array = [‘H’, ‘e’, ‘e’, ‘l’, ‘l’, ‘o’];
array.reverse();     // returns [‘o’, ‘l’, ‘l’, ‘e’, ‘H’]

3. join: This function accepts a string argument and combines array elements with the argument in between those elements. Example,

let array = [‘H’, ‘e’, ‘e’, ‘l’, ‘l’, ‘o’];
array.join(‘#’);    // returns H#e#l#l#o#

All these functions can be used to reverse a string as shown in the example below.

Reversed string is <span id="result"></span>
<script>
   // declare string to reverse
   let str = "codippa";

   function reverseUsingInbuiltFunctions() {
      // get all characters of string in array
      let characters = str.split('');
      // reverse characters of array
      let reverseArray = characters.reverse('');
      // join array elements with an empty string
      let reversedString = reverseArray.join('');
      return reversedString;
   }
   // get reversed string
   let reverseStr = reverseUsingInbuiltFunctions(str);
   // display reversed string
   document.getElementById("result").innerHTML = reverseStr;
</script>

Function for reversing the string defined above can be combined into a single line.

function reverseUsingInbuiltFunctions() {
return str.split('').reverse('').join('');
}

Method 4: Using spread operator
This method is similar to the previous method but it uses spread operator instead of split to break the string into an array of characters.
spread operator consists of square brackets containing the string variable preceded with 3 periods(…).
Remaining code remains the same. Example,

Reversed string is <span id="result"></span>
<script>
   // declare string to reverse
   let str = "codippa";

   function reverseUsingInbuiltFunctions() {
      /* use spread operator to get all characters
of string in array */
      let characters = [...str];
      // reverse characters of array
      let reverseArray = characters.reverse('');
      // join array elements with an empty string
      let reversedString = reverseArray.join('');
return reversedString;
   }
   // get reversed string
   let reverseStr = reverseUsingInbuiltFunctions(str);
   // display reversed string
   document.getElementById("result").innerHTML = reverseStr;
</script>

Above code can be replaced with a one-liner as below

let str = "codippa";
let characters = [...str].reverse('').join('');

Using ES6 syntax, the function defined above can be written using an arrow function as

const reverseUsingInbuiltFunctions = str => [...str].reverse('').join('');

These were 4 different methods of reversing a string in javascript.
Hope the article was useful for you.

Exit mobile version