-
Notifications
You must be signed in to change notification settings - Fork 27
Open
Description
Given the test case below
...
titleCase('HERE IS MY HANDLE HERE IS MY SPOUT'); // Here Is My Handle Here Is My Spoutfunction 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.
\bmatches the word boundary\wmatches the first letter of each word(\w+)matches more or more letter of each word- The
gflag is used to replace all occurrences of the regex in the string
Metadata
Metadata
Assignees
Labels
No labels