Will this Regex Logic fail for Title Casing?

TitleCasing a Sentence


 return str.toLowerCase().replace(/^(\w)|(\s\w)/g, (L) => L.toUpperCase());

Here is a RegexChecker


  1. Identity the first letter of the sentence using ^(\w)
  2. Find all letters after a space (\s\w)
  3. combine them /^(\w)|(\s\w)/g

I am gloating on the solution as I understand ReGex now a bit better thanks to FCC but I am not sure where this expression would fail in different examples for TitleCasing.

Wanted to know some opinions on it.

| is OR. So the regex says “from the start of the string (^), match if the first character is a word character (A-Z, a-z, 0-9 or _) OR if it is a space character followed by a word character”. Then you are uppercasing the match. It only ever matches the first one or two characters of the entire string.

The regex matches the first letters of each word in the string, but also the spaces. As this challenge only requires you to uppercase the first letter at the beginning or after a space, your regex works fine because space is case insensitive, so I think you did a good job.

If you wanted to leave behind the spaces you could use positive lookbehind (but it’s not very well supported by the browsers yet) or just split the string, for example.