Algorithm
- Input: Take the input string that needs to be reversed.
- Initialize Variables: Create variables to store the reversed string and the length of the input string.
- 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.
- Build Reversed String: As you iterate through the characters, concatenate each character to the reversed string.
- 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
Enter a string: hello world
dlrow olleh
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
Enter a string: hello
olleh
olleh
Demonstration
JavaScript Programing Example to Reverse a String-DevsEnv