Using replace() with Regular Expression

When using the titleCase function the first letter in each word is replaced (wanted result) but the spaces are deleted (unwanted result).

The moment I use a use the toUpperCase() on the replacing value (like in the commented out row) the spaces are not deleted (wanted result)!

What is going on!? Why?

Note: I solved the challenge in 2 much less elegant ways and stumbled on this question when trying to understand the third given solution in the hints section.

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

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

Challenge: Title Case a Sentence

Link to the challenge:

Your expression matches a space (or the beginning of a line) followed by a non-space. Both of those characters are part of the pattern, so they are both being replaced by the single character “x”. When you use toUpper you are calling a method that replaces letters with uppercase by does not change non-letter characters.

In the first line you are replacing a two character string with a single character. In the second case you are replacing a two character string with a two character string.

1 Like

Wow thanks! That’s just what I needed

I’m glad I could help. Happy coding!