Javascript Bytes (3): Capitalize Each String

A simple but effective coding challenge to practice Javascript syntax!

Problem: Write a function that will capitalize the first letter of each word in a sentence.

var string = “this is my sentence”;

First, we need to make an array out of this sentence in order to parse through it and find the beginning of each word (which is at index 0).

We use the split string method to separate each word in the array by the spaces in the original string.

var stringArray = string.split(” “);

Now, stringArray should look like this:

[“this”, “is”, “my”, “sentence”];

Sweet! We can now utilize the power of arrays to solve our problem! Now, to find the beginning letter of each word, we need to access each substring of the string. Once we have access to each substring, we need to split that word apart and change the correct letter to solve the problem. In our case, the problem is asking for the beginning letter of each word to be capitalized. Since we need to capitalize the first letter of each word, we will need to use a loop.

function capitalizeWord(string) {

var stringArray = string.split(” “);
//potential bug, create stringLength as a variable
var stringLong = stringArray.length;
//empty array
var array = [];

for (var i = 0; i < stringLong; i++) {

var newArray = stringArray[i];
var capitalizedLetter = newArray.substring(0, 1).toUpperCase() + newArray.substring(1);


//format the joined array into string
return array.join(” “);


capitalizeWord(“hello world, how are you today?”);

As we see above, before we return the modified array, we need to join it back into a string. So, we utilize the join method in order to achieve this.






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s