Make first letter of array statement uppercase in JS

Viewed 399

I have an array, and I want to convert the first letter to a capital by using map

const arrayTOCapital = [
  'hi world',
  'i want help ',
  'change first letter to capital',

 ];

const arrayFirstLetterToCapital = () => {
  return arrayTOCapital.map(function(x){ return 
      x.charAt(0).toUpperCase()+x.slice(1) })
}

The output should be:

Hi World
I Want Help
Change First Letter To Capital
3 Answers

You can just use a regular expression /\b\w/g to find all letters preceeded by a word boundary (such as whitespace) and replace it with capitalized version

const arrayTOCapital = [
  'hi world',
  'i want help ',
  'change first letter to capital',
];

console.log(arrayTOCapital.map(x => x.replace(/\b\w/g, c => c.toUpperCase())));

You need to apply the same logic on every word in the sentences, and then join them as follows:

const arrayTOCapital = [
  'hi world',
  'i want help ',
  'change first letter to capital',

];

const arrayFirstLetterToCapital = () => { 
     return arrayTOCapital.map(function(x){ 
          return x.split(" ").map(function(y){
               return y.charAt(0).toUpperCase()+y.slice(1);
          }).join(" ");
     });
}

console.log(arrayFirstLetterToCapital());

const arrayTOCapital = [
  'hi world',
  'i want help',
  'change first letter to capital'
 ];
 
 const results = arrayTOCapital.map(
   str => str.split(' ').map(s => s[0].toUpperCase() + s.substr(1)).join(' ')
 )
 
 console.log(results);

You can add an extra .join(' ') after the last bracket if you are looking to make a single sentence.

Related