Given the test case below
...
titleCase('HERE IS MY HANDLE HERE IS MY SPOUT'); // Here Is My Handle Here Is My Spout
function titleCase(str) {
return str.replace(/\b\w/g, (match) => match.toUpperCase());
}
The solution above only replaces first matched letter and ignores the rest of the letters in a word, assuming that they are all in lowercase.
// a more accurate soltuion would be
function titleCase(str) {
return str.replace(/\b\w(\w+)/g, (word, restWord) => `${word[0].toUpperCase()}${restWord.toLowerCase()}`);
}
Explanation
The regex /\b\w(\w+)/g matches the first letter of each word and groups the rest of the letter in a word.
\b matches the word boundary
\w matches the first letter of each word
(\w+) matches more or more letter of each word
- The
g flag is used to replace all occurrences of the regex in the string
Given the test case below
The solution above only replaces first matched letter and ignores the rest of the letters in a word, assuming that they are all in lowercase.
Explanation
The regex
/\b\w(\w+)/gmatches the first letter of each word and groups the rest of the letter in a word.\bmatches the word boundary\wmatches the first letter of each word(\w+)matches more or more letter of each wordgflag is used to replace all occurrences of the regex in the string