Geek Culture
Published in

Geek Culture

Algorithms and Data Structures Part VII

Capitalize…

Photo by Diomari Madulara on Unsplash

O.k. so this is going to be a shorter problem than the last few but I will once again go into as much detail as possible in the hopes it will help you understand better.

For this problem we’re asked to write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.

E.G. capitalize(‘a short story’) → ‘A Short Story’

Before we start working on this problem let's look at a little tip.

First, let's look at the .slice() method. Slice is used on a string to take some number of elements out of that string.

str.slice(beginIndex[, endIndex])

The first argument is the index of that string to start from and there is an optional second argument of the end index, if you don’t provide the second argument the rest of the string is automatically included.

Let’s get started…

We have our empty function with a string argument. Now we will declare an empty array called words.

Then we want to loop through our string, to do this we will need to split it by spaces.

str.split(‘ ‘) will split each word that has a space in between it E.G.

const sentence = 'well hello there'
sentence.split(' ') --> ["well","hello","there"]

now we have three individual words.

Now whatever string gets passed in here so long as it is a sentence with spaces in between the words, will be split up by the split statement.

Next let’s take the first character of each word a.k.a. word[0] and we will uppercase it by calling .toUpperCase() then join it back to the rest of the word by using the slice function.

word[0].toUpperCase() + word.slice(1) 

now just push the result into the words empty array.

words.push(word[0].toUpperCase() + word.slice(1))

Finally, we want to take the words array and join it together with a space character.

words.join(' ')

and we want to return the result…

return words.join(' ')

the entire code looks like this…

So like I said, there’s not a lot of code here but it’s still a little tricky if you don’t know these few tips.

I hope you enjoyed this and thanks for reading!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store