-1

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
2
  • 2
    Array.prototype.join() returns the joined string. You're not doing anything with its return value. Commented Mar 3, 2022 at 9:59
  • Please try this: console.log(('This is a beautiful day').split(' ').map(w => w[0].toUpperCase() + w.slice(1)).join(' '));. The capitalizedName.join(' '); returns a string - it does not mutate the array capitalizedName. So, if you simply say console.log(capitalizedName.join(' ')); - it should provide the desired result. Commented Mar 3, 2022 at 10:16

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

You need to reassign the variable capitalizedName as a string

capitalizedName = capitalizedName.join(' ');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.