0

It was supposed to capitalize first characters of each string but it doesn't. Please tell me how I can solve this problem.

    let array = ["string1", "string2", "string3", "string4"];
    let btn = document.getElementById("btn");

    array.forEach(function (item) {
      item.charAt(0).toUpperCase();
    })

    btn.addEventListener("click", function () {
      document.getElementById("p").innerHTML = array.join(" ")
    })```
1
  • You've to create a new string in the loop, strings in JS are immutable. Commented Jan 19, 2022 at 20:05

1 Answer 1

-1

You are getting the first letter and converting it to uppercase, but you aren't doing anything with it.

You need to concatenate the rest of the string to the first character, then reassign back.

let array = ["string1", "string2", "string3", "string4"];

array.forEach(function(item, i) {
  array[i] = item.charAt(0).toUpperCase() + item.substring(1)
})

console.log(array.join(" "))

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.