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

JavaScript

why they wont accept my answer of this challenge in freecodecamp?

hello i was just wondering why the wont accept my answer. i tested in my computer and it works fine. but when i submitted the answer it says its wrong. i would highly appreciate if someone can help me to better understand the problem thank you. here is my code

 function titleCase(str) {
    let words = str.toLowerCase().split(' ');
    let newStr = '';

    for (let i = 0; i < words.length; i++) {
        newStr += words[i][0].toUpperCase() + words[i].slice(1) + ' ';
    }
    return newStr;
}

console.log(titleCase('upper case the first letter of each word'));
rydavim
rydavim
18,813 Points

Given that your function works just fine, you'll need to provide a link to where you're working on this problem in order for anyone to evaluate why it's failing there. You can either edit your post, or add a comment below (like this) to include a link.

1 Answer

rydavim
rydavim
18,813 Points

You are adding an extra space to your returned string, causing the challenge to fail. It's hard to catch, since you can't see it in the output, but you can test with length.

("I'm a little tea pot").length; // 20
titleCase("I'm a little tea pot").length; // 21

You've got several options for how you want to work around that, but the rest of your code looks good. Let me know if you run into any problems, and we can walk through a solution together. Happy coding!

yeah you are right, i didnt think about the length. but i guess it matters in the challenge i was stuck in this problem for a few hours and i was pretty close. but is my solution a good or bad practice? i found the solution in the internet and it was pretty close

function titleCase(str) {
    let words = str.toLowerCase().split(' ');

    for (let i = 0; i < words.length; i++) {
        words[i] = words[i][0].toUpperCase() + words[i].slice(1);
    }
    return words.join(' ');
}

titleCase("i'm a little tea pot");

thank you so much for helping me

rydavim
rydavim
18,813 Points

There are many ways to solve this, and there are upsides and downsides to each. Having not gone through that particular external course, it's difficult for me to say what's "best". If you're interested in exploring other solutions, this write-up by camperbot looks good to me.