Capitalize words in the string with array.map and string methods

Share this video with your friends

Social Share Links

Send Tweet

Learn how write a function that capitilizes words in the string from the scratch. We will use map array method, some native string functions and overall apply functional programming approach to solve this popular interview question.

Dimitri Ivashchuck: [0:00] In this lesson, we'll learn how to answer an entry question, which tasks you with upper case in 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 upper case.

[0:18] Let's write the function first, const capitalizeString, and then this function accepts string. Then, we want to perform some operations on it.

[0:33] The first thing that we need to do is actually to split the whole string that we got, to been able to perform operations on each individual word. 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. In our case, we want to split it by space, so each individual word being split by space.

[1:18] It doesn't matter if we put comma somewhere, it will still split it. This we want to perform the uppercase on the first letter, it doesn't matter. Let's log the splitString to see what we get. We involve 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 older individual strings. Let's write another const, would be the capitalizedStringArray and we want to map through the splitString that we got 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 the each letter which is 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 the first character removed. We already perform the uppercase separation on it, and then concatenate them together with plus separator. 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 again, we want to join by the space. Let's log result, and we get the quick brown fox jumps over the lazy dog, but all the words in the string capitalized.

[3:51] To finally finish our function, we want to return the result. Without all the console logs, it will look something like this.