📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Reversing a string is a common task in programming. In JavaScript, the built-in reverse()
function is available for arrays, but if you want to reverse a string without using this built-in function, there are several alternative approaches you can use, such as:
- Using a for loop to reverse the string.
- Using recursion to reverse the string.
- Using array manipulations like manually swapping characters.
This guide will walk you through writing a JavaScript program to reverse a string using different methods.
Problem Statement
Create a JavaScript program that:
- Takes a string as input.
- Reverses the string without using the built-in
reverse()
function. - Outputs the reversed string.
Example:
- Input:
"hello"
- Output:
"olleh"
Solution Steps
- Using a for loop: Traverse the string from the end to the beginning and build a reversed string.
- Using recursion: Use a recursive function to reverse the string.
- Using array manipulations: Convert the string to an array, manually reverse the array, and then join the array back into a string.
JavaScript Program
Method 1: Reverse a String Using a For Loop
// JavaScript Program to Reverse a String using a For Loop // Author: https://www.rameshfadatare.com/ function reverseStringForLoop(str) { let reversed = ''; for (let i = str.length - 1; i >= 0; i--) { reversed += str[i]; } return reversed; } // Example usage const inputString = "hello"; console.log("Original String:", inputString); console.log("Reversed String (For Loop):", reverseStringForLoop(inputString));
Method 2: Reverse a String Using Recursion
// JavaScript Program to Reverse a String using Recursion // Author: https://www.rameshfadatare.com/ function reverseStringRecursion(str) { if (str === '') { return ''; } else { return reverseStringRecursion(str.substr(1)) + str.charAt(0); } } // Example usage console.log("Reversed String (Recursion):", reverseStringRecursion(inputString));
Method 3: Reverse a String Using Manual Array Manipulation
// JavaScript Program to Reverse a String using Manual Array Manipulation // Author: https://www.rameshfadatare.com/ function reverseStringArray(str) { let charArray = str.split(''); let start = 0; let end = charArray.length - 1; // Swap the characters at the start and end positions while (start < end) { let temp = charArray[start]; charArray[start] = charArray[end]; charArray[end] = temp; start++; end--; } // Convert the array back to a string return charArray.join(''); } // Example usage console.log("Reversed String (Array Manipulation):", reverseStringArray(inputString));
Explanation
Method 1: Using a For Loop
- This method initializes an empty string
reversed
. It then iterates through the input string from the last character to the first, appending each character toreversed
. Finally, the reversed string is returned.
Method 2: Using Recursion
- The recursive function splits the string into two parts:
- The first character (
str.charAt(0)
). - The remaining string (
str.substr(1)
). - It then recursively reverses the remaining string and appends the first character at the end.
- The base case occurs when the string becomes empty.
- The first character (
Method 3: Using Array Manipulation
- The input string is split into an array of characters using
split('')
. - A loop is used to swap the characters from the start and end of the array until the middle is reached.
- The array is then joined back into a string using
join('')
.
Output Example
Original String: hello Reversed String (For Loop): olleh Reversed String (Recursion): olleh Reversed String (Array Manipulation): olleh
Conclusion
This JavaScript program demonstrates three different methods to reverse a string without using the built-in reverse()
function. Each method is efficient and helps illustrate various ways of solving the problem using loops, recursion, and array manipulation. Understanding these approaches will enhance your problem-solving skills in JavaScript.
Comments
Post a Comment
Leave Comment