JS Algorithm – Capitalize the first letter

Big Ben, London, United Kingdom

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(‘a lazy fox’) –> ‘A Lazy Fox’
capitalize(‘look, it is working!’) –> ‘Look, It Is Working!’

First solution:

function capitalize(str) {
  // To save every capitalize word
  const words = [];

  // Go through every position in the array
  // at same time creating an array with every word
  // ["look,"]
  // ["it"]
  // ["is"]
  // ["working!"]
  for (let word of str.split(' ')) {
    // Taken the first word of the array
    // converting to upper case
    // and adding the other part of the characters
    words.push(word[0].toUpperCase() + word.slice(1));
  }

  // Converting the array to string
  return words.join(' ');
}

capitalize('look, it is working!');

Result:

Second solution:

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

  for (let i = 1; i < str.length; i++) {

    // check if the left character of the current character
    // is space
    if (str[i - 1] === ' ') {
      // take the current character and upper case it
      // and adding to the result string
      result += str[i].toUpperCase();
    } else {
      // just add the current character to the string
      result += str[i];
    }
  }

  return result;
}

capitalize('look, it is working!');

Result:

By Cristina Rojas.