Just finished the ‘Title Case a Sentence’ task, and I’ve looked through other results on the forum but nothing is at all similar to mine that I’ve seen. Have I been really inefficient about this? I’ve only used one for loop and one new variable, but should I be doing something differently? I kinda feel like a kid still counting on my fingers here haha. Like it gets the result, but there must be a more elegant way…
Thanks for any advice
function titleCase(str) {
str = str.toLowerCase();
str= str.split(" “);
var result = “”;
for (i =0;i< str.length;i++){
result += str[i][0].toUpperCase();
result += str[i].slice(1);
result += " “;
}
result = result.replace(/\s*$/,””);
return result;
}
The point is you can apply logic to the pass the test, personally I try not to worry if my solutions could be smaller, not at this stage at least. Maybe because i know they always could.
Looking at the above from kevcomedia… its great but theres no way i would have come up with that at the time.
Good point I did actually stop and have that moment of realisation, that it was the first time id got to the point of reflection. So far it’s been ‘does it work? Ok done’. And slightly more recently ‘do I actually understand why it works? Kinda? Ok done!’ haha
But yeah, as long as it works, and could work for any input (rather than being designed just to pass those particular tests) I’m pretty happy at this point. Onwards and upwards!
Commenting out the code at each section when finished is a very good way to understand the jibberish i’ve just typed out I find
I also go check the wiki to see exactly how the better soultions work… no cheating tho! you’re only allowed to do that if passed, i’ll be watching haha
Yeah, I agree with MARKJ78… kevcomedia gave a great solution, but I wouldn’t have been able to (and didn’t) come up with something like that as I was working through these algorithms. My solution was pretty much the same as MARKJ78, I even wrote a blog post about my long ass solution here… LOL! Live and learn.