Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,786 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,786 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,786 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.