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

You should read the documentation for using a function with replace and a regular expression.

You have a couple syntax issues with your current code. First, I think the regular expression you wanted to use was:




You had a backslash where forward slash should have been.

That [A-Z] part is not going to do anything. Putting [A-Z], JavaScript is assuming you are putting an array with one element of A-Z, but since A or Z have not been defined as variables, you get an error.

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.