DEV Community

loading...

Discussion on: Daily Challenge #38 - Middle Name

Collapse
joeberetta profile image
Joe Beretta

Not the best solution: ))

function findMiddleName(str) {
    const words = str.split(' ');
  let result = '';
  if(words.length <= 2)
    return result = str
   else{
   let middleNames = ''
   for(let i = 1; i < (words.length - 1); i++)
    middleNames += (words[i].slice(0,1) + '. ') 
    return result = `${str.split(' ')[0]} ${middleNames}${str.split(' ')[words.length - 1]}`
   }
}

console.log(findMiddleName('Jack Ryan'));
console.log(findMiddleName('Lois Mary Lane'));
console.log(findMiddleName('Dimitri'));
console.log(findMiddleName('Alice Betty Catherine Davis'));