Capitalizing first letter of each word in a string

Tell us what’s happening:
I apologize for my frequent questions, but I don’t understand why the code fails to return the correct result when dealing with the “I’m a little tea pot” string

Your code so far


function titleCase(str) {
  return str.toLowerCase().replace(/\b(\w)/g, r => r.toUpperCase());
}

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

Your browser information:

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

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

Here is what you code return for the str = “I’m a little tea pot”

//I’M A Little Tea Pot

You should find a way to handle that “M”

I solved the problem by doing function titleCase(str) { return str.toLowerCase().replace(/\b(\w)/g, r => r.toUpperCase()).replace(/'m/i, m => m.toLowerCase()); }But that will only work for that specific example, are there any better ways of dealing with it?

Positive lookaheads perhaps?

How would that work? Examples?

Not much I can do without giving the answer unfortunately.

But you can mess with regex in this site:
https://regexr.com/

Comes with explanations of what regex you used!

1 Like

Thank you, I will take a look at the website