Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Function to reverse a string JavaScript
In JavaScript, reversing a string is a common programming task that can be accomplished using various approaches. This tutorial demonstrates how to create a function that reverses any given string by iterating through its characters in reverse order.
Understanding the Problem
String reversal means rearranging the characters of a string so that the last character becomes first, second-last becomes second, and so on. For example, if we have the string "Hello", the reverse will be "olleH".
Algorithm
Step 1 ? Declare a variable to store the reversed string and initialize it as empty.
Step 2 ? Iterate through the characters of the input string using a for loop, starting from the last character.
Step 3 ? Inside the loop, append each traversed character to the reverse string variable.
Step 4 ? Return the completed reversed string.
Method 1: Using For Loop
// Function to reverse the given string
function reverseStr(str) {
let reverse = '';
for (let i = str.length - 1; i >= 0; i--) {
reverse += str[i];
}
return reverse;
}
const str = "Hello JavaScript";
console.log("Original string:", str);
console.log("Reversed string:", reverseStr(str));
Original string: Hello JavaScript Reversed string: tpircSavaJ olleH
Method 2: Using Built-in Methods
JavaScript provides built-in array methods that can simplify string reversal:
function reverseStrBuiltIn(str) {
return str.split('').reverse().join('');
}
const testString = "JavaScript";
console.log("Original:", testString);
console.log("Reversed:", reverseStrBuiltIn(testString));
Original: JavaScript Reversed: tpircSavaJ
Method 3: Using Recursion
function reverseStrRecursive(str) {
if (str === '') return '';
return reverseStrRecursive(str.substr(1)) + str.charAt(0);
}
const recursiveTest = "Recursion";
console.log("Original:", recursiveTest);
console.log("Reversed:", reverseStrRecursive(recursiveTest));
Original: Recursion Reversed: noisruceR
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| For Loop | O(n) | O(n) | Good |
| Built-in Methods | O(n) | O(n) | Excellent |
| Recursion | O(n) | O(n) | Good |
Complexity Analysis
All methods have O(n) time complexity because we need to process each character once, where n is the length of the input string. The space complexity is also O(n) for storing the reversed string characters.
Conclusion
String reversal in JavaScript can be achieved through multiple approaches. The built-in methods approach using split(), reverse(), and join() is most concise, while the for loop method provides better understanding of the underlying logic.
