DEV Community

Realised-Prophets
Realised-Prophets

Posted on

Reversing a string

I'm currently working through freeCodeCamp's 300h javascript course. One of the algorithm challenges is to reverse a string. I solved this with a for loop, unshift() and join() like this:

function reverseString(str) {
  let arr = [];
  for (let i = 0; i < str.length; i++) {
    arr.unshift(str[i]);
  }
  return arr.join(""); 
}

reverseString("Hello")

Enter fullscreen mode Exit fullscreen mode
  1. I declared an empty array to store the separate characters.

  2. I wrote your usual FOR loop to iterate through the input string characters.

  3. I used the unshift method because this pushes each new letter to the front, starting with H into my empty arr variable. It iterates though it like this:

[ 'H' ]
[ 'e', 'H' ]
[ 'l', 'e', 'H' ]
[ 'l', 'l', 'e', 'H' ]
[ 'o', 'l', 'l', 'e', 'H' ]
Enter fullscreen mode Exit fullscreen mode

so by the end of the loop you end up with this array of letters which are in the reverse order.

4 . Now I have an array with the desired order, however, the challenge wants a single string. A quick google search provided me with the .join() method, which I then use on my arr variable. The result is olleH

When I finished I looked up a few other ways of doing this. I'll post them another day!

Love, RP

Top comments (1)

Collapse
 
frankwisniewski profile image
Frank Wisniewski
console.log( 
  reverseString("H❤️ell🙌🙌o")
)
Enter fullscreen mode Exit fullscreen mode

returns

o�🙌�lle️❤H
Enter fullscreen mode Exit fullscreen mode