JavaScript Program to Reverse a String

Introduction

Reversing a string is a common task in programming, where the order of characters in a string is reversed. For example, reversing the string "hello" results in "olleh". This program demonstrates how to reverse a string in JavaScript using simple and efficient methods.

Problem Statement

Create a JavaScript program that:

  • Accepts a string.
  • Reverses the string.
  • Returns the reversed string.

Example:

  • Input: "hello"

  • Output: "olleh"

  • Input: "JavaScript"

  • Output: "tpircSavaJ"

Solution Steps

  1. Read the Input String: Provide the string either by user input or directly within the code.
  2. Reverse the String: Split the string into an array of characters, reverse the array, and then join the characters back into a string.
  3. Display the Result: Print the reversed string.

JavaScript Program

// JavaScript Program to Reverse a String
// Author: https://www.javaguides.net/

function reverseString(str) {
    // Step 1: Split, reverse, and join the string
    let reversedStr = str.split('').reverse().join('');
    return reversedStr;
}

// Example input
let inputString = "hello";
let result = reverseString(inputString);
console.log(`The reversed string is: ${result}`);

Output

The reversed string is: olleh

Example with Different Input

let inputString = "JavaScript";
let result = reverseString(inputString);
console.log(`The reversed string is: ${result}`);

Output:

The reversed string is: tpircSavaJ

Explanation

Step 1: Split, Reverse, and Join the String

  • The split() method is used to split the string into an array of individual characters.
  • The reverse() method reverses the order of the characters in the array.
  • The join() method combines the characters back into a string, producing the reversed version of the original string.

Step 2: Display the Result

  • The reversed string is printed using console.log().

Conclusion

This JavaScript program demonstrates how to reverse a string using built-in methods such as split(), reverse(), and join(). This approach is both simple and efficient for reversing strings of any length. It can be extended or modified to handle more complex string manipulations.

Comments