How to Reverse a String in Javascript


Let's learn how to reverse a string in Javascript using 5 different ways with examples.

Reversing a string is a very common task in programming. Generally it is not the main task to reverse a string but it comes as a small part of some bigger tasks. So it's worth knowing how to reverse a string in Javascript.

    Table Of Contents

  1. Methods to reverse a string
    1. Using split and join
    2. Using for loop (Fastest ⭐️🥇)
    3. Using while loop
    4. Using recursion
    5. Using stack
  2. Performance of above methods
  3. Conclusion

How to reverse a string in javascript

Methods to Reverse a String in Javascript

There can be various ways to reverse a string in Javascript. In this article, we have discussed 5 different ways of this. You can choose any one of these that suits your requirement.

Also, you can see the performance comparison of all these methods below to know which one is faster.


1. Using split and join

The first method to reverse a string is by using the split() and join() methods.

The idea here is to split the string into an array and then reverse the array and then join the array back to a string.

The code to reverse a string using split and join is given below.

Example

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

var str = "TutorialsTonight";
console.log(`${str} reversed is '${reverseString(str)}'`);

The above code uses the reverse() method of the Array class to reverse the array of characters of the string.

All three methods are chained together. You can also use these methods separately.

You can look at the same example to understand working step by step.

Example

function reverseString(str) {
  var split = str.split('');
  console.log(split);

  var reverse = split.reverse();
  console.log(reverse);

  var join = reverse.join('');
  console.log(join);
  return str.split('').reverse().join('');
}

var str = "TutorialsTonight";
console.log(`${str} reversed is '${reverseString(str)}'`);

Run the code above to see the task in action.


2. Using for loop (Fastest ⭐️🥇)

for loop is a universal tool to solve almost any problem in programming (if you know how to solve it).

The idea here is to loop through each character of the string from end to start and then start adding them to a new string.

This way we can reverse the string. Here is the code for this.

Example

function reverseString(str) {
  var reversed = '';
  for (var i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

var str = "TutorialsTonight";
console.log(`${str} reversed is '${reverseString(str)}'`);

3. Using while loop

The while loop is another way to solve the problem.

Again we follow the same approach as above but this time we use the while loop to reverse the string.

The code for this is given below.

Example

function reverseString(str) {
  var reversed = '';
  while (str.length > 0) {
    reversed += str.charAt(str.length - 1);
    str = str.substring(0, str.length - 1);
  }
  return reversed;
}

var str = "TutorialsTonight";
console.log(`${str} reversed is '${reverseString(str)}'`);

The charAt() method is used to get the character at a particular index of string. And substring() method is used to get the part of the string from the start index to the end index.


4. Using recursion

The recursion is a programming concept that is used to solve the problem by calling the same function again and again with some change in the input parameters.

Using recursion we can reverse the string.

Example

function reverseString(str) {
  if (str.length === 0) {
    return '';
  }
  return reverseString(str.substring(1)) + str.charAt(0);
}

var str = "Hello";
console.log(`${str} reversed is '${reverseString(str)}'`);

In the above code, recursion stops when the length of the string is 0. This is the base case. Otherwise, it returns reverseString(str.substring(1)) + str.charAt(0) which is calling the same function again by leaving out the first character of the string and adding the first character of the string to the end.

Every time program runs the same thing happens and we get the reverse of the string.


5. Using stack

Stack is a data structure that is used to store data in LIFO (last in first out) manner. We can use this to reverse the string.

We will use LIFO (last in first out) feature of the stack and put each character of string in the stack and then pop them out one by one. By popping out the characters we will get characters in reverse order.

Add them to a new string and return the string.

Example

function reverseString(str) {
  var stack = [];
  for (var i = 0; i < str.length; i++) {
    stack.push(str[i]);
  }
  var reversed = '';
  while (stack.length > 0) {
    // pop out the last character of String
    reversed += stack.pop();
  }
  return reversed;
}

var str = "TutorialsTonight";
console.log(`${str} reversed is '${reverseString(str)}'`);

Performance of above methods

The above methods are used to reverse the string. The time taken to reverse the string is dependent on the length of the string but for the same length of string, the time taken by each method is different.

It's always preferred to use the fastest method to solve the problem.

Let's see the time taken by each method. Methods are references as Method1, Method2, Method3, and so on.

Example

// Performance of all methods
var time1, time2;

// Method 1:
function reverseString1(str) {
  return str.split('').reverse().join('');
}
time1 = new Date();
for (var i = 0; i < 1000000; i++) {
  reverseString1('hello');
}
time2 = new Date();
console.log(`Method 1 took ${time2 - time1} milliseconds`);

// Method 2:
function reverseString2(str) {
  var newString = '';
  for (var i = str.length - 1; i >= 0; i--) {
    newString += str[i];
  }
  return newString;
}
time1 = new Date();
for (var i = 0; i < 1000000; i++) {
  reverseString2('hello');
}
time2 = new Date();
console.log(`Method 2 took ${time2 - time1} milliseconds`);

// Method 3:
function reverseString3(str) {
  var newString = '';
  while (str.length > 0) {
    newString += str.charAt(str.length - 1);
    str = str.substring(0, str.length - 1);
  }
  return newString;
}
time1 = new Date();
for (var i = 0; i < 1000000; i++) {
  reverseString3('hello');
}
time2 = new Date();
console.log(`Method 3 took ${time2 - time1} milliseconds`);

// Method 4:
function reverseString4(str) {
  if (str.length === 0) {
    return '';
  }
  return reverseString4(str.substr(1)) + str.charAt(0);
}
time1 = new Date();
for (var i = 0; i < 1000000; i++) {
  reverseString4('hello');
}
time2 = new Date();
console.log(`Method 4 took ${time2 - time1} milliseconds`);

// Method 5:
function reverseString5(str) {
  var stack = [];
  for (var i = 0; i < str.length; i++) {
    stack.push(str[i]);
  }
  var newString = '';
  while (stack.length > 0) {
    newString += stack.pop();
  }
  return newString;
}
time1 = new Date();
for (var i = 0; i < 1000000; i++) {
  reverseString5('hello');
}
time2 = new Date();
console.log(`Method 5 took ${time2 - time1} milliseconds`);

The above code will run 1000000 times and will give the time taken by each method.

The fasted method is Method2 which is using for loop to reverse the string.


Conclusion

This is the end of the brief guide to reverse a string in JavaScript. The fasted method we have seen is reversing the string using for loop to reverse string.