How To Capitalize Words In A Sentence (JavaScript)

Believe it or not, there is no magical method to capitalize words in a string. Not only is this a very common algorithm, but it is a common task. Just like the words in the title of this blog, sometimes capitalizing each word makes things look good!

function capitalizeWordsInASentence(str) {
    //Split string in an array
    const words = [];

    //Iterate thru values and split values into array by spaces
    for(let word of str.split(' ')) {
        //push onto array --- upper case first word -- slice the rest of the word
        words.push(word[0].toUpperCase() + word.slice(1));
    }
    //Rejoin values with spaces
    return words.join(' ');
}
  • Iterate through each word in the array
  • Uppercase the first letter of the word
  • Join first letter with rest of the string
  • Push result into ‘words’ array

Using charAt()

function capitalizeWordsInASentence(str) {
    const words = [];

    for(let word of str.split(' ')) {
       words.push(word.charAt(0).toUpperCase() + lower.slice(1);
    }

    return words.join(' ');
}

    

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *