Algorithm


  1. Input: Take the input string that needs to be reversed.
  2. Initialize Variables: Create variables to store the reversed string and the length of the input string.
  3. Iterate Through Characters: Use a loop to iterate through each character of the input string.
    • Start the loop from the last character and move towards the first character.
  4. Build Reversed String: As you iterate through the characters, concatenate each character to the reversed string.
  5. Output: The reversed string is the final result.

 

Code Examples

#1 Code Example- Reverse a String Using for Loop

Code - Javascript Programming

// program to reverse a string

function reverseString(str) {

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

// take input from the user
const string = prompt('Enter a string: ');

const result = reverseString(string);
console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: hello world
dlrow olleh

#2 Code Example- Reverse a String Using built-in Methods

Code - Javascript Programming

// program to reverse a string

function reverseString(str) {

    // return a new array of strings
    const arrayStrings = str.split("");
   
    // reverse the new created array elements
    const reverseArray = arrayStrings.reverse();
 
    // join all elements of the array into a string
    const joinArray = reverseArray.join("");
    
    // return the reversed string
    return joinArray;
}
 
// take input from the user
const string = prompt('Enter a string: ');

const result = reverseString(string);
console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: hello
olleh
Advertisements

Demonstration


JavaScript Programing Example to Reverse a String-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way