Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ira Salem
10,331 PointsReversing a string in JS
I'm trying to reverse the string "hello" but I keep getting an error message with this code. What am I doing wrong? I know that I'll have to split the string first which should turn the string into an array that contains 'h','e','l','l', and 'o'. Then I reverse them and then join them back together but I can't even get past the first step.
function reverseString(str) {
return str;
}
reverseString.split(("hello", ""));
2 Answers
Jacob Mishkin
23,118 PointsThere are several ways you can do this. I suggest using the reverse() method, like so:
function reverse(s) {
return s.split('').reverse().join('');
}
by returning the split() and reverse() and join() methods what is happing here is that you first split the string into array, then call the reverse() method, then you put it back together with the join() method.
there are a lot of other ways to reverse a string, but I think this is the most effective way. I hope this helps.
Ira Salem
10,331 PointsThank you so much. That worked perfectly
Jacob Mishkin
23,118 PointsIra not a problem. Any time.
Andrew Dummer
6,885 PointsIra, In your reverseString(), please try returning myArray instead of str and using str.split('') instead of str.split(' '). That should get you past your first step.
Ira Salem
10,331 PointsIra Salem
10,331 PointsHere is my new code. I'm still not getting what I want. What am I doing wrong?