DEV Community

loading...

Discussion on: Daily Challenge #38 - Middle Name

Collapse
andymardell profile image
Andy Mardell

Javascript

This was fun :)

const initialiseMiddleNames = (fullName) => {
  const names = fullName.split(' ')
  if (names.length <= 2) return fullName

  const firstName = names.shift()
  const lastName = names.pop()
  const initials = names.map(name => name.charAt(0))

  return `${firstName} ${initials.join('. ')}. ${lastName}`
}

initialiseMiddleNames('Jack Ryan') // Jack Ryan
initialiseMiddleNames('Lois Mary Lane') // Lois M. Lane
initialiseMiddleNames('Dimitri') // Dimitri
initialiseMiddleNames('Alice Betty Catherine Davis') // Alice B. C. Davis