Spot the bug - #118: Name Badge Generator

My cute wizard title formatter keeps printing undefined words.

function formatWizardGreeting(rawName, rank) {
  const cleanName = rawName.trim();
  const safeRank = rank.toLowerCase();

  let prefix = '';
  if (safeRank === 'archmage') {
    prefix = 'The Grand';
  } else if (safeRank === 'apprentice') {
    prefix = 'Novice';
  } else {
    prefix = 'Traveler';
  }

  // Capitalize first letter of wizard name
  const firstChar = cleanName.charAt(0).toUpperCase();
  const restOfName = cleanName.subString(1).toLowerCase();
  const styledName = firstChar + restOfName;

  const magicBanner = `*~ ${prefix} ${styledName} ~*`;
  return magicBanner.repeat(1);
}

const greeting = formatWizardGreeting('  gANDALF ', 'archmage');
console.log(greeting);

Reply with what is broken and how you would fix it.

The subString method is misspelled. It should be substring with a lowercase ‘s’. JavaScript string methods are case-sensitive, so subString isn’t found, leading to undefined in the output.

const restOfName = cleanName.substring(1).toLowerCase();

Spot the Bug answer: The String.prototype.subString method is misspelled as subString instead of substring.

The fix:

Change cleanName.subString(1) to cleanName.substring(1).

Why:
JavaScript string methods are case-sensitive. The correct method name for extracting a part of a string is ‘substring’ (all lowercase). Using ‘subString’ results in a TypeError because the method does not exist on the String prototype, causing the restOfName variable to be undefined and leading to ‘undefined’ in the output.

First-answer leaderboard

  1. @kirupa - 4 (firsts) :trophy:
  2. @adnanahmed - 2 (firsts)
  3. @emmawalter5 - 1 (first)