skip to Main Content
const capitalizeName = function (name) {
  const names = name.split(` `);
  const uppercasedName = [];

  for (const n of names) {
    //uppercasedName.push(n[0].toUpperCase() + n.slice(1));
    uppercasedName.push(n.replace(n[0], n[0].toUpperCase()));
  }
  console.log(uppercasedName.join(''));
};
capitalizeName('jessica ann smith davis ');

console shows the problem lies in upperName part but when i remove space in name.split(‘ ‘) code will work but this time caps all the string letters

2

Answers


  1. Because

    capitalizeName('jessica ann smith davis ');
    

    has a trailing space,

    name.split(` `);
    

    puts an empty element at the end of names

    Either remove the space or trim before splitting:

    const capitalizeName = function (name) {
        const names = name.trim().split(' ');
        const upperName = [];
    
        for (const n of names) {
            //upperName.push(n[0].toUpperCase() + n.slice(1));
            upperName.push(n.replace(n[0], n[0].toUpperCase()));
        }
        console.log(upperName.join(''));
    };
    capitalizeName('jessica ann smith davis ');
    

    Edit: @jdkramhoft shows a third option in his answer: validating n inside the for loop.

    Login or Signup to reply.
  2. Your example is breaking because of the space at the end of 'jessica ann smith davis ' and works fine for 'jessica ann smith davis'.

    This is because split will identify the trailing space as an empty word. The easiest way to work around this with what you have would be to not attempt to uppercase undefined strings. If you want spaces between the final result you would join with a space character join(' '):

    const capitalizeName = function (name) {
      const names = name.split(` `);
      const upperName = [];
    
      for (const n of names) {
        n && upperName.push(n.replace(n[0], n[0].toUpperCase()));
      }
      return upperName.join(' ')
    };
    console.log(capitalizeName('jessica ann smith davis '));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search