Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my method is not reversing the string

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It works when I trace it on paper.

>Solution :

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 = 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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading