0

Can anyone tell me why I can't do this way? I know convert to array first, but why? Thanks!

function reverseString(s){
    if(s.length<2){return s}
    var i=0, j=s.length-1;
    while(i<j){
        var temp = s[i];
        s[i]=s[j];
        s[j]=temp;
        i++;
        j--;
    }
    return s
}
Steven
  • 61
  • 2
  • 6
  • Possible duplicate of [How do you reverse a string in place in JavaScript?](https://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript) – Tom O. Feb 02 '18 at 15:39
  • Thanks. This is wrong code because I did not turn it into an array. I'm wondering why this code not work – Steven Feb 02 '18 at 15:41
  • 1
    Just follow it logically. Using your example code, `abcd` becomes `dbca`, then `dcba`, then `dbca` and then finally `abcd`. Basically, if you stopped half way through your loop your code would have worked, but you keep going so you reverse it and then reverse it again. – Reinstate Monica Cellio Feb 02 '18 at 16:02

2 Answers2

1

Strings are immutable. You can never change them.

They have numeric properties that allow you to read individual characters, but those properties are readonly (if you could write to them, the string wouldn't be immutable).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

You could use recursion to reverse a string without converting the string to an array.

This code will basically slice the last character from the input string and append it to the accumulator, it will continue calling itself until the input string no longer has any characters where it will return the accumulator string.

As a bonus it's tail recursive so in modern browsers you could process a string of any size.

As alluded to above, strings are immutable so you won't get the same string out as you put in but you probably don't need to worry about that.

const reverse= (xs, acc = '') =>
  !xs.length
    ? acc
    : reverse(
        xs.slice(0, -1), // get the start of the string
        acc.concat(xs.slice(-1)) // append the end of the string to the accumulator
      )
    
console.log(
  reverse('.gnirts rotalumucca eht nruter lliw ti erehw sretcarahc yna sah regnol on gnirts tupni eht litnu flesti gnillac eunitnoc lliw ti ,rotalumucca eht ot ti dneppa dna gnirts tupni eht morf retcarahc tsal eht ecils yllacisab lliw edoc sihT')
)

console.log(
  // you can even use it on an array if you change the accumulator to an array
  reverse(['one', 'two', 'three'], [])
)

console.log(
  // or you could put it into an array
  reverse('reverse', [])
)
synthet1c
  • 6,152
  • 2
  • 24
  • 39