DEV Community

loading...

Discussion on: Daily Challenge #38 - Middle Name

Collapse
goodidea profile image
Joseph Thomas

Here's mine, with a more functional approach - also takes into account name strings that have erroneous spaces

jsbin.com/gedejih/edit?js,console

function formatName(name) {
    /* Trim out any spaces at the beginning or end,
     * split the name into segments,
     * and filter out empty strings. */
  const splitName = name
    .trim()
    .split(' ')
    .filter(n => n.length > 0)

  return splitName.map((namePart, index) => {
    /* Return the first and last names as they are */
    if (index === 0 || index === splitName.length - 1) return namePart

    /* Otherwise, get the first character,
     * make sure it is capitalized,
     * and return it with a `.` */
    return `${namePart[0].toUpperCase()}.`

  }).join(' ')
}


const formattedNames = names.map(formatName)