Get the initials from a name

“Initials”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 2: Data Types: What Goes in the Boxes? teaches, and 3 tests check your answer.

The challenge

Write initials(fullName) that returns the first letter of each word, in capitals. Names are separated by single spaces.

Example
initials("Mia Grace Rossi")  // "MGR"
initials("omar khan")        // "OK"

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

  • initials("Mia Grace Rossi") gives "MGR"
  • initials("omar khan") gives "OK"
  • initials("Zoe") gives "Z"

Hints

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

Hint 1

Loop over the characters: a letter is a “first letter” if it’s at index 0 or comes right after a space.

Hint 2

Or, after Grade 7, fullName.split(" ") gives you the words.

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 initials(fullName) {
  let result = "";
  for (let i = 0; i < fullName.length; i++) {
    if (i === 0 || fullName[i - 1] === " ") {
      result += fullName[i].toUpperCase();
    }
  }
  return result;
}

Learn what you need

This exercise uses what Grade 2: Data Types: What Goes in the Boxes? 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