🎓 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 (178K+ 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment