Basic Algorithm Scripting: Title Case a Sentence -- Help Me Understand This Reg Ex

Title Case a Sentence

Please help me understand the regular expression used in the solution of this problem:

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());

Particularly, this code:


I understand what all three characters are used for: the caret, the pipe character, and the white space character. However, what I don’t understand is how the white space character in this instance is being used to denote characters or a string that occur after white space.

What I understand of the white space character from the relevant lesson is that it can be used to actually find white space, like spaces, tabs, return, etc. Does the existence of the pipe operator mean something other than “or”?

This pattern captures two “characters”: the start-of-line character or whitespace character and a non-whitespace character. It then replaces that two “character” match with the uppercase version of itself.

1 Like

Ah, thanks. It all makes sense now!

I’m glad I could help. Happy coding.