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
Because
has a trailing space,
puts an empty element at the end of names
Either remove the space or trim before splitting:
Edit: @jdkramhoft shows a third option in his answer: validating n inside the for loop.
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(' ')
: