Write a capitalize string function with array and string methods

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

In this lesson we will use functional programming approach to solve the challenge which requires you to capitalize all the letters of the string passed to the function. We will employ array.map together with string.split and string.join to achieve this functionality.

Dimitri Ivashchuk: [0:00] In this lesson, we'll learn how to answer an interview question which tasks you with uppercasing the words in the string. Given this string for example, we need to run a function that returns the same string but with each word being in uppercase.

[0:18] Let's write the function first, const capitalizeString. Then this function accepts string. Now we want to perform some operations on it. The first thing that we need to do is actually to split the whole string that we got to being able to perform operations on each individual word.

[0:46] Let's do that first, const splitString = string.split. Split method of the string accepts an argument which is also a string, and you pass the value by which you want to split.

[1:08] In our case, we want to split it by space, so each individual word being split by space. It doesn't matter if we put comma somewhere, it will still split it. Unless we want to perform the uppercase on the first letter, it doesn't matter.

[1:33] Let's log the splitString to see what we get. We involve with the capitalizeString function and pass testString to it, and we see that it yielded us the array of each individual word.

[1:50] Now, we can perform some operation on this array, and capitalize all the individual strings. Let's write another const would be the capitalizedStringArray, and we want to map through the splitString that we get so through this array, and we want to get the value.

[2:21] Let's try to first, get the uppercase first letter from each individual word. We use native string method toUpperCase, and let's log capitalizedStringArray. You see that we now get each letter which is a capitalized version from each string, but we're missing the other part of the word, so we just need to append it.

[2:59] We want to slice the value and get first character removed. We already perform the UpperCase operation on it, and then concatenate them together with plus operator. Let's save it.

[3:17] Finally, we want to join all these words into the string, so it looks like a normal string that we passed through it. Const result would be capitalizedStringArray join, and together, we want to join by the space.

[3:39] Let's log result, and we get the quick brown fox jumps over the lazy dog, but all the words in the string capitalized. To finally finish our function, we want to return the result. Without all the console logs, it will look something like this.