Title Case a Sentence?

Tell us what’s happening:

Your code so far


function titleCase(str) {
  let strWords=str.toLowerCase().split(" ");
  for (let i=0;i<strWords.length;i++)
  {
  //  strWords[i].split("");
    strWords[i].replace(charAt(0),charAt(0).toUpperCase());
    //strWords[i].join("");
  }
  str=strWords.join(' ');
  return str;
}

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

Your browser information:

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

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

oh sorry I guess I missed out that last part, what my question was. I couldnt get it to work, cause first I tried doing the first letter capitalization by splitting each substring and capitalizing the first letter and then rejoining the substring to form the word. But the error I got was strWords[i].join is not a function. Those are the commented lines.

Then I used replace and I got it to work

I think this problem can be solved using regex too although Im not sure how

strWords[i].replace(charAt(0), charAt(0).toUpperCase());

charAt(0) should be str.charAt(0).

And you’ll almost be there…

Can this problem be solved by using regex as well?

okay let me give that a go too. Thanks

@kerafyrm02: Yes that what I eventually used to solve this problem

.replace() & regex would be my choice of solving this problem.

Actually,. you could do this with .reduce() too.

@kerafyrm02 I thought reduce was just to combine all numerical values of an array and add them

You can combine anything. Not just numbers.

gotcha. ill try that too

To take back what I stated earlier., to solve this problem I would make a ucase function and use .map().

Typo., result would be abbcc

1 Like

Np. I didn’t know it was optional is only reason I spotted it.

So it seems whenever it’s omitted the first element becomes the initial value.

YUes, I did solve it by using the replace function to make the first letters uppercase, I was just trying to get a handle on different ways of solving the problem. Thanks for your input guys

I’m an advocate for functional programming. Both functions are reusable.

const ucfirst = (word) => word[0].toUpperCase() + word.slice(1);
const ucwords = (sentence) => sentence.split(' ').map((word) => ucfirst(word)).join(' ');

I borrowed the function names from PHP.