SPOILER! Title Case a Sentence

I have my own variation of the answer, this code passes the test. But I’m wondering if it’s alright to write it this way.
The answers provided in FCC all had something to do with replacing the first character in the array to an uppercase with .replace() but throughout my code, I never used .replace().

Your code so far

function titleCase(str) {
let arr = str.split(’ ');

for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].toLowerCase();
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1);
}

return arr.join(’ ');
}

console.log(titleCase(“sHoRt AnD SToUt”));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence

That works - either way you have recreated the word with the first letter capitalized. There are many ways you could have solved this one. The provided solutions tend to be limited to material already covered in previous challenges and / or to topics the lesson is demonstrating.

Since yours is a working solution could you edit your post to wrap that code in spoiler tags so that someone looking for help does not accidentally see the answer?

[spoiler]
Your code inside
[/spoiler]

Thank You!

1 Like

I did something similar actually, though with a chained map instead of a for loop

But don’t worry about comparing to the provided answers in general, they’re examples of ways to approach the problem

They’re often not the ‘best’ way to do a problem (for some suitable definition of best, e.g. most performant or most readable), but they may show a way to solve them that you didn’t think of

Just because the answers don’t do things precisely the same way doesn’t mean your solution was wrong or anything

1 Like

@gebulmer @alhazen1 Thank you guys! I was just wondering if the solutions given were a better way of solving things as I don’t want to carry any bad habits forward. And I will wrap it with the spoiler tag, thanks for letting me know :smile:

What if,someone will write a sentence like this one?