A simple way of reversing a string is as below:
const test = 'hello';
let i = 0;
let j = test.length - 1;
while (i < j) {
let temp = test[i];
test[j] = test[i];
test[i] = temp;
i++;
j--;
}
console.log(test);
If we try to access string using an index it works fine. For example console.log(test[2])
returns 'l'
But reversing a string using the method above returns unchanged string 'hello'
. We need to use an array, reverse it and then join it to return the reversed string. But in that case we will be using an extra space. Can we do it without using an extra space?