Signup/Sign In
PUBLISHED ON: FEBRUARY 17, 2023

JavaScript Program to Reverse a String

Have you ever come across a situation where you needed to reverse a string using JavaScript? This is a common problem that can be solved using various methods. In this article, we will explore two methods to reverse a string using JavaScript, and we'll guide you through step-by-step, so you can write a program that can reverse any string you input.

Approach

Before we jump into the solution, let's first understand the problem. Reversing a string means to flip the order of the characters in the string. For instance, if we have the string "hello", the reversed string would be "olleh".

There are many methods to reverse a string in JavaScript, some of them are discussed below:

Method 1 : Program to Reverse a String Using for Loop

A for loop is used to iterate over the strings from behind. It starts from str.length - 1 , which is basically the last position. That element is added to the newString variable, which represents the reversed string.

// JavaScript Program to reverse a string

function reverseString(str) {

 
    let newString = "";
    for (let i = str.length - 1; i >= 0; i--) {
        newString += str[i];
    }
    return newString;
}

const string = prompt('Enter a string: ');

console.log(reverseString(string));


Enter a string: hello javascript
tpircsavaj olleh

Method 2 : Program to Reverse a String Using built-in Methods

  • The split function is used to split the words in character elements
  • The reverse method is used to reverse the elements given.
  • The reversed strings are joined by into a cumulative sentence using the join method.
// JavaScript program to reverse a string

function reverseString(str) {

    // return a new array of strings
    const arrayStrings = str.split("");
   
    const reverseArray = arrayStrings.reverse();
 
    // join all elements of the array into a string
    const joinArray = reverseArray.join("");
    
    return joinArray;
}

const string = prompt('Enter a string: ');

console.log(reverseString(string));

?


Enter a string: hello javascript
tpircsavaj olleh

Conclusion

In this article, we have discussed two methods to reverse a string using JavaScript. Whether you use the split() and reverse() method or a for loop, you can easily reverse any string in no time. It's essential to understand the problem before diving into the solution.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.