Convert a string to title case

“Title Case”, a Green belt challenge from the CurlyScript Dojo. It uses what Grade 7: Arrays: Lists of Things teaches, and 3 tests check your answer.

The challenge

Write titleCase(sentence) that makes the first letter of each word uppercase and the rest lowercase.

Example
titleCase("the lion KING")  // "The Lion King"

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • titleCase("the lion KING") gives "The Lion King"
  • titleCase("welcome") gives "Welcome"
  • titleCase("a b c") gives "A B C"

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

split(" ") into words, fix each word, then join(" ").

Hint 2

For one word: word[0].toUpperCase() + word.slice(1).toLowerCase().

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function titleCase(sentence) {
  const words = sentence.split(" ");
  const fixed = [];
  for (const w of words) {
    fixed.push(w[0].toUpperCase() + w.slice(1).toLowerCase());
  }
  return fixed.join(" ");
}

Learn what you need

This exercise uses what Grade 7: Arrays: Lists of Things teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning