Search code examples
javascriptuppercase

Make first letter of array statement uppercase in JS


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

Solution

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