Reverse a String: Why Am I Not Passing?

Tell us what’s happening:
I don’t know why I’m not passing this challenge. Every phrase I’ve entered in the function has reversed correctly, including the test ones.

  **Your code so far**

function reverseString(str) {
str = [...str]

for (let i = (str.length-1); i >= 0; i--){
  let popped = str.pop()
  str.splice((str.length - i),0,popped)
  str = [...str]
}

str = str.toString();

let regex = /,/g;
let removed = ''
str = str.replace(regex,removed);
console.log(str)

}

//reverseString("");



  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15

Challenge: Reverse a String

Link to the challenge:

OK it was literally just because I was missing a return statement. Since I was seeing everything show up in the console I was confused.

Was looking at this for ages and of course only realized right after posting :man_facepalming:

Welcome to coding. :grinning: Wait 'til you spend three days looking for a missing semicolon!

Glad you found the error.

jrm

1 Like

OP, I’m glad you solved the problem on your own. That said, you’ve got some weird stuff going on.


Remember that you can access characters of a string via their index.

const name = "Colin"

console.log(name[2]) // "l"

In your code you’re needlessly converting between the string to an array and back to a string again. You absolutely do not need to do this.


Remember also that you can build up a string using the += operator to append one string to another.

let name = "C";
name += "o";
name += "l";
name += "i";
name += "n";

console.log(name) // "Colin"

What I’m saying is, you’re overcomplicating this quite a bit. You can solve this problem with just a for loop and string concatenation.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.