Home > Blockchain >  How to join the elements of an array such that the first letter is capital for all elements in JavaS
How to join the elements of an array such that the first letter is capital for all elements in JavaS

Time:03-02

I want to join the elements of an array separated by commas and the first letter of each element to be capital, this should not affect the object values itself.

For example:

obj= ["apple","orange","lemon"]

Output should be: Apple, Orange, Lemon.

Here is what I have tried and failed with:

obj.charAt(0).toUpperCase().join(', ')

CodePudding user response:

Here is the code:

let a = ['apple', 'orange', 'lemon'];
let res = a.map(fruit => fruit.charAt(0).toUpperCase()   fruit.slice(1));
console.log(res); // [ "Apple", "Orange", "Lemon" ]

CodePudding user response:

const fruits = ["apple", "orange", "lemon"];

const new_fruits =
  fruits
    .map(x => x.replace(/^[a-z]/, (ch) => ch.toUpperCase()))
    .join(", ");

Replace first letter a-z, uppercase it and finally join with commas. Readability ftw.

  • Related