Skip to content
Home » Blog » JavaScript Program to Reverse a String

JavaScript Program to Reverse a String

JavaScript Program to Reverse a String

In this program, you’ll be learning how to Reverse a String in JavaScript

This Program is requested by one of the Instagram followers, and this question is asked in a lot of interviews, the interviewers may ask you about this program

There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.

Below is program to reverse the string ins JavaScript.

Program to Reverse a String With Recursion

function reverseString(str) {
  if (str === "")
    return "";
  else
    return reverseString(str.substr(1)) + str.charAt(0);
}
reverseString("hello");

For this solution, we will use two methods: the String.prototype.substr() method and the String.prototype.charAt() method.

JavaScript Program to Reverse a String

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

"hello".substr(1); // "ello"
  • The charAt() method returns the specified character from a string.
"hello".charAt(0); // "h"

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.

Related Programs:

  1. C Program
  2. C++ Program
  3. Python Program
  4. Java Program

Ask your questions and clarify your doubts by commenting.