Title Case a Sentence - RegEx Query

Title Case a Sentence - RegEx Query
0

#1

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”);


#2

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.


#3

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:

/\b[a-z]/g

not

/\b[a-z]\g

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.


#5

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


#6

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