Capitalizing First Letter of Every Word in an Array of Sentences

·

2 min read

To get started I have an array of strings:

const arrayTitles = [
  'what does the this keyword mean?',
  'What is the Constructor OO pattern?',
  'implementing Blockchain Web API',
  'The Test Driven Development Workflow',
  'What is NaN and how Can we Check for it',
  'What is the difference between stopPropagation and preventDefault?',
  'Immutable State and Pure Functions',
  'what is the difference between == and ===?',
  'what is the difference between event capturing and bubbling?',
  'what is JSONP?'
];

My approach would be to take each element in the array in this case, each sentence, and convert it into an array like so:

['what', 'does', 'the', 'this', 'keyword', 'mean','?']

To do this, we will use the split method for each sentence. However, we will have to loop through the arrayTitles array so to do that we are going to use the map method. We use the map method to return a new array with the changed elements. Anytime we want to do something on some elements of an array, it's alway a good idea to leave the original array unchanged. Let's get started!

const caseTitles = () => {
//first we want to loop through our arrayTitles
  const wordsWithCapLetters = arrayTitles.map((sentence)=>{
    //here we want to split the sentence into an array of words
    const sentenceArray = sentence.split(' ')
    //now we want to loop through those array of words 
    //to get the first letter and capitalize it
    const sentenceWithCapsArray = sentenceArray.map((word)=>{
    // we use the slice method on the word to get the first letter
    // and we use the toUpperCase method to capitalize it
      const capLetter = word.slice(0,1).toUpperCase()
     // in order to add the caplitalized letter to the rest of the word
    // we are going to grab the rest of the word using slice again
      const restOfWord = word.slice(1)
    // now we can add the capitalized letter to the rest of the word 
      return capLetter + restOfWord
    })
    //once every letter of the first word has been capitalized 
    //we can use the join method to put the sentence we split up
    //back together using the join method
    return sentenceWithCapsArray.join(' ')
  })

  return wordsWithCapLetters
}

And that is it! We have now successfully capitalized every first letter of the words in our arrayTitles array!

Here are the links for more information on the methods we used and how they work.

map method

split method

slice method

toUpperCase method

join method