Home > OS >  Unable to convert an array back to string by using join(" ")
Unable to convert an array back to string by using join(" ")

Time:03-03

I initially have a string whose words first letter I want to capitalize. After capitalization, I'm unable to convert the array back to string. What's wrong here?

const name = 'This is a beautiful day';
console.log(name)
const capitalizedName = name.split(' ');
for (let i = 0; i < capitalizedName.length; i  ) {
capitalizedName[i] =
  capitalizedName[i][0].toUpperCase()   capitalizedName[i].substr(1);
}
capitalizedName.join(' ');
console.log(capitalizedName);

The output:-

This is a beautiful day
[ 'This', 'Is', 'A', 'Beautiful', 'Day' ]

Output that I was expecting:-

This is a beautiful day
This Is A Beautiful Day

CodePudding user response:

You need to reassign the variable capitalizedName as a string

capitalizedName = capitalizedName.join(' ');

CodePudding user response:

you don't reassign capitalizedName after join function

you can also use map function on split array to manipulate word each other

const name = 'This is a beautiful day';
console.log(name);
let capitalized = name.split(' ')
   .map(word => word[0].toUpperCase()   word.substr(1))
   .join(' ');
console.log(capitalized);

  • Related