Javascript Algorithms: Capitalize First Letter of Each Word In a Sentence

JavaScript Algorithms: Capitalize the First Letter of Each Word in a Sentence

As I prepare for Javascript development interviews I've been reviewing various online articles and resources about different algorithms I'll likely get asked about. Turns out that these things are actually pretty fun exercises and while I was able to do some of them all by my lonesome, others required some documentation lookups and Googling. Like any development problem there are likely multiple good solutions but the ones I present here are probably the most direct and obvious - feel free to solve differently and generate your own solution.

Where possible I'll cite my source(s) and give credit to any resources that helped me solve this algorithm.

CAPITALIZE THE FIRST LETTER OF EACH WORD IN A SENTENCE

Resources:

https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/sentence-capitalization

Write a solution in Javascript where, if I give you a standard English sentence you'll return that sentence with each word capitalized. For example, if I provide "Here is my sentence" your solution will return "Here Is My Sentence".

USAGE: Copy and paste the code samples below into the Javascript console in your browser, then simply hit return on your keyboard to see the code in action.

//CAPITALIZE THE FIRST LETTER OF EACH WORD IN A SENTENCE
function capSentence(text) {
    let wordsArray = text.toLowerCase().split(' ')  /*lowercase everything and split the string 
	on each space char*/
    let capsArray = []  //create a new array to use 

    wordsArray.forEach(word => {  //loop over each word....
        capsArray.push(word[0].toUpperCase() + word.slice(1))  /*add each word to the new 
		capsArray, making the first char upper and appending the remaining chars to the end 
		of the array element*/
    });

    return capsArray.join(' ')  /*piece together the caps array into the array we previously 
	declared */
}; 

console.log(capSentence("Here is my sentence."));


Copyright 2019. All Rights Reserved.