How do you JavaScript reverse string in-place within a function, using a return statement, without relying on built-in methods like .reverse() or .charAt()?
To reverse a string in JavaScript without using built-in methods like .reverse() or .charAt(), you can achieve this manually by iterating through the string and reconstructing it.
You can loop/ iterate through the string from the end to the beginning and build a new string by appending each character in reverse order.
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseString("hello")); // Output: "olleh"
This method uses two pointers, one starting at the beginning and the other at the end of the string. The characters are swapped until they meet in the middle.
function reverseString(str) {
let arr = str.split('');
let left = 0;
let right = arr.length - 1;
while (left < right) {
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr.join('');
}
console.log(reverseString("hello")); // Output: "olleh"