Title Case a Sentence - RegEx Query

I’m trying to capitalise the first letter of every word in a sentence using JS RegEx. I think that I’ve identified what I want to replace with ‘str.replace’, but now I don’t know how to replace lowercase with uppercase.

It looks to me like my expression says “Find characters at the beginning of words, that are lowercase, for the whole sentence, and then replace them with uppercase”.

All thoughts are appreciated!

function titleCase(str) {
//reg exp to identify and replace first letter
var rep = str.replace(/\b[a-z]\g/, [A-Z] );

return rep;
}

titleCase(“I’m a little tea pot”);

The replace function can accept a function as its second argument, which describes what it does with the matches.

Maybe you meant /\b[a-z]/g ? I can’t find anything about \g.

1 Like

Many thanks, that’s something to work with now. I was unsure about [A-Z], it helps knowing that it’s not a value.

Using a function as an argument sounds doable, thanks for that.