Skip to content

title-case second solution is incorrect. #3

Description

@mades-g

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions