0

I know there are many other ways to reverse a string in JS but I wrote this and it is not working and I want to understand why. Mine only has two extra parameters so I can tell it to reverse from here to there.

function strRev(str, startRev, endRev) {
    while (startRev < endRev) {
        let temp = str[startRev];
        str[startRev] = str[endRev]; 
        str[endRev] = temp;

        startRev += 1; 
        endRev -= 1;
    }
    return str;
}

And usage:

let str = "STACK";
strRev(str, 0, str.length -1 ); 

But what I get as result is the same original string. I don't understand why.

It works when I trace it on paper.

  • @Terry did you read the text, it answers why – epascarello Feb 12 '23 at 15:12
  • @Terry so if needed I could tell it to reverse just part of a word or if it is a whole sentence with space in betweens, I can say keep reversing until you see a white space etc ... – FromThisLaptop Feb 12 '23 at 15:12
  • 3
    Strings do not work like arrays changing indexes. Simple test `var str = 'foo'; str[0] = 'b'; console.log(str);` – epascarello Feb 12 '23 at 15:13
  • I strongly encourage you to move to [JavaScript modules](//developer.mozilla.org/en/docs/Web/JavaScript/Guide/Modules) or at least enable [strict mode](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode). Your code throws an error there which makes it obvious as to why this does not work. `str.split("")` counterintuitively splits by UTF-16 code units, which is not something you usually want. `.slice` behaves the same way. [Do _not_ use `.split("")`](/a/38901550/4642212). Use `Array.from(string)` to split by characters instead. – Sebastian Simon Feb 12 '23 at 15:27

2 Answers2

1

You can not set the character of a string using the index with bracket notation.

To do what you are trying to do, you need to use an array and not a string.

function strRev(orgStr, startRev, endRev) {
  const str = Array.from(orgStr); // orgStr.split('');
  while (startRev < endRev) {
    let temp = str[startRev];
    str[startRev] = str[endRev];
    str[endRev] = temp;

    startRev += 1;
    endRev -= 1;
  }
  return str.join('');
}


let str = "STACK";
console.log(strRev(str, 0, str.length - 1));
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Your algorithm is correct, but you need to change how you modify the string

Unfortunately you can't poke individual characters into a string, like you are trying to do.

Doubly unfortunately, trying to do so does not cause an error in Javascript.

function strRev(str, startRev, endRev) {
  while (startRev < endRev) {

    str = str.slice(0, startRev) + str[endRev] + str.slice(startRev + 1, endRev) + str[startRev] + str.slice(endRev + 1)
 
    startRev += 1;
    endRev -= 1;
  }
  return str;
}


let str = "STACK";

console.log(strRev(str, 0, str.length - 1));
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26