2

I have following string array

let example = ["hello", "what"];

I want to convert this array's to this:

 ["Hello", "what"];

To accomplish that I have following code:

example[0][0] = example[0][0].toUpperCase();

When I try to console.log(example), I get

["hello", "what"]

What's wrong here? How can I convert first element's first letter to upper case?

3
  • 3
    Strings cannot be changed. You have to make a completely new string and replace example[0]. Commented Feb 2, 2020 at 16:33
  • @Pointy Yes, that's the correct answer, but why we cannot directly modify a string? Commented Feb 2, 2020 at 16:41
  • Do you only want "Hello" to be capitalized, and not also "what", as the question states? Commented Feb 2, 2020 at 16:48

5 Answers 5

2

I hope that can help.

let example = ["hello", "what"];

example = example.map(ar => ar[0].toUpperCase() + ar.slice(1));
Sign up to request clarification or add additional context in comments.

Comments

1

Try this one

example = ["hello", "eat"];
var camelCaseArray = [];
for(var x = 0; x < example.length; x++){
    camelCaseArray.push(example[x].charAt(0).toUpperCase()+example[x].slice(1));
}
console.log(camelCaseArray)

Comments

0

Try this.

let example = ["hello", "what"];

example[0] = example[0].charAt(0).toUpperCase() +  example[0].substring(1);

console.log(example);

1 Comment

Does not provides the required result. The second string should be lowercase.
0

try this one too.

let example = ["hello", "what"];

example[0] = example[0].charAt(0).toUpperCase() + example[0].slice(1);
console.log(example);

Comments

-1

Why do you have two square brackets? You only need one...

example[0]=example[0].toUpperCase();

1 Comment

That produces: ["HELLO","what"]

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.