Capitalizing Each Word In A Sentence with JavaScript

·

2 min read

Capitalizing Each Word In A Sentence with JavaScript

Instructions

Write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.

// Examples
capitalize('a short sentence') // 'A Short Sentence'
capitalize('not like this') // 'Not Like This'
capitalize('learning to code!') // 'Learning To Code!'

This turned out to be slightly harder than I originally expected. However I got there in the end.

Solution

Create a empty words array. Split the given string by spaces to get an array. Loop over each word using forEach. Uppercase the first letter, join this letter to the rest of the string. Push the result into the words array. Join the words array by spaces and return the result.

const capitalize = (str) => {
    //empty array
  const words = []
    // split string and itterate over each word
  str.split(' ').forEach((word) => {
        // uppercase the first letter and join the rest of string. 
        // push result to words array
    words.push(word[0].toUpperCase() + word.slice(1))
  })
    // join words and return
  return words.join(' ')
}

Instead of using the forEach array helper you are able to use for to loop over the split string.

const capitalize = (str) => {
  const words = []
  for (let word of str.split(' ')) {
    words.push(word[0].toUpperCase() + word.slice(1))
  }
  return words.join(' ')
}

Solution 2

Create a string called result. Setting it to the first character of the input string and make it upper case. Iterate through each letter in the string starting at 1. Check if the character to the left has a space. If so capitalize the current letter and add it to the result variable. Else add it to result.

function capitalizeFor(str) {
  let result = str[0].toUpperCase()

  for (let i = 1; i < str.length; i++) {
    if (str[i - 1] === ' ') {
      result += str[i].toUpperCase()
    } else {
      result += str[i]
    }
  }

  return result
}