Now, there are a number of ways to do this. You could loop over each one of the elements. You could create some kind of starter string. You could say something like this, or it’s just creating the string. You start with it just being an empty string. You go through, and you loop through each one of the words. You pipe it into the strong. That would be a valid way of doing it. I wanna show you a way that I personally think is a little bit cleaner, it’s more of a functional approach. Hopefully, you’ll enjoy going through this one.
I’m gonna start by creating a function called, toCapital. This is going to take a string as an argument and it’s going to be an arrow function. Inside of here, the very first thing that I wanna do, is I want to break up this string, into a set of words. The way we can do that, is with the split function. I can say const words = string.split. I wanna split it at each space. The way you can do that is by saying split, and then the argument to split is where you want it split at. If we wanted … Say, this was a CVS file and you wanted it split at each comma, you’d say split, with a comma inside of it, and then it’d break each one of those into it’s own element. For right now, I want to split it, so that each word is gonna be converted.
Now, let’s see what this looks like. If I can toCapital, and then I pass it … Let’s pass it the long string. You can see that we’re getting undefined, cause I need to return this. Here I’ll say, return words. There you go. You can see that we’re getting an array of the words. They’re all split up the way that we’ve want. That’s the first step. Really, we only have one more line of code, in order to get this working. Instead of returning words, what I wanna do is, return words. I wanna map over it. I want to iterate over the collection of words we just created, and run a process here. Word takes a function. I’m gonna make it an arrow function.
When I say shortStr, this is grabbing me, the very first element. That is exactly what I’m wanting. I’m gonna say, word, and then I want to cast this, or change it to upper case. What that’s gonna do is, that is going to grab the first element and then it is going to convert it, no matter what it is. If it already is upper case, it’s going to keep it that way. If it is lower case, it’s gonna make it upper case. From there, I simply want to add on to the rest of the words.
For this very first example … For the quick brown fox … For this one, it’s going to loop over the word. It’s going to give me the. It’s going to take the T, it’s going to make that upper case. What we need is we need to get access to the H and the E, and then combine them. The way we can do that is with the slice method. I can say, word.slice and pass in a one. Now, if you have never seen this before, let’s take a look at what this is going to do. If I say, let’s just grab some word … Let’s just call it word actually. Just make it nice and easy…
Full coding guide and source code: