Title Case a Sentence - Advanced Regex Solution Question

Tell us what’s happening:
While the code works, I’d like to understand why the regex in parentheses (^|\s) works. The ^ should include the first character and the \s includes white space. Why does the \s select the character following white space and the ^ selects the first character, not the character following the first character (character 2)?

Your code so far


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

titleCase("I'm a little tea pot");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence/

The part in parentheses is a choice between beginning of line OR a space character. The next part means followed by a non space character. So you are essentially matching the first char of a sentence or of a word

1 Like

I think this just made sense, just to clarify, the beginning of the line ^ means before any character on the line but the empty space before a character, correct?

It actually just signifies the beginning of the line so it doesn’t match any character not even spaces

1 Like

Thanks for the help!

You are welcome :blush: