Write a function that takes a string as input and returns the string reversed.
September 17, 2024
Reversing a string is a common interview question for JavaScript developers. Here’s a detailed explanation, including the problem statement, various methods to solve it, and a brief discussion of their time and space complexities.
//string reverse
Input: "bpthink"
Output: "knihtpb"
Input: "JavaScript"
Output: "tpircSavaJ"
In the Javascript we have a few methods to reverse a string
Method:1 Using Built-in Functions
function reverseString(str) {
return str.split('').reverse().join('');
}
// Test the function
console.log(reverseString("bpthink")); // Output: "knihtpb"
console.log(reverseString("JavaScript")); // Output: "tpircSavaJ"
[/code]//built-in functions
function reverseString(str) {
return str.split('').reverse().join('');
}
// Test the function
console.log(reverseString("bpthink")); // Output: "knihtpb"
console.log(reverseString("JavaScript")); // Output: "tpircSavaJ"
Code Breakdown:
- Convert the string to an array: Use the
.split('')
method to split the string into an array of characters. - Reverse the array: Use the
.reverse()
method to reverse the order of the elements in the array. - Join the array back into a string: Use the
.join('')
method to combine the elements of the array back into a string.
Method:2 Using a For Loop
//Using For Loop
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
// Test the function
console.log(reverseString("bpthink")); // Output: "knihtpb"
console.log(reverseString("JavaScript")); // Output: "tpircSavaJ"
Code Breakdown:
- Initialize an empty string.
- Loop through the input string from the last character to the first character.
- Append each character to the new string.
No comments yet.