Basic Algorithm Scripting: Reverse a String*

If you know how to go forwards through a string or array using a for loop then you know how to go backwards in a string or array. It’s the same concept except you start at the other end. You are very close, you just have two issues:

  • You are still not starting ‘i’ at the correct spot. If there are 5 elements in an array, the length of the array is 5 but what is the index number of the last element? (HInt: it’s not 5.) It’s the same concept for strings.
  • You are not setting lastLetter correctly. Remember, ‘i’ is a counter for each character in your string. It starts at the last character in the string and works its way down to the first character. It represents a numbered position in your string. How do you access a specific element in an array? Again, it’s the same concept for strings. If you are unsure what the value of ‘i’ is during each loop then put a console.log(i) inside the for loop.

It is done!

function reverseString(str) {
let reversedLetter="";
let lastIndexOfStr=str.lastIndexOf('');        
       //console.log(lastIndexOfStr); 
  for (let i=str.lastIndexOf('');i>=0;i--){
 
 let character = str.charAt(i);

          reversedLetter+=character;
        
          console.log(reversedLetter)  
          }
          return reversedLetter;     
    }

reverseString("hello");

In order to solve this, you need to know the answer to this question:

How do you find the index number of the last element in an array?

Once you have the answer then you will know how to set the initial value of i in the for loop.

Also, you do not need a variable to hold the last letter in the string. There is nothing special about that letter. You will be going through all of the letters in the string (backwards). What you need is a variable to hold the new reversed string you are creating in the for loop. So change reversedLetter to reversedString because that is what you are creating. And then don’t forget to return reversedString at the end of the function.

I am thankful for explaining this.