Skip to content
Advertisement

How do I solve this JavaScript titlecase problem with an empty string?

I’m new to JavaScript and am having a bit of trouble with this problem:

Construct a function called titleCase that takes a sentence string and gives it title casing.

JavaScript

This is the code I’ve tried:

JavaScript

It is passing all tests except for the empty string "" test.

Advertisement

Answer

You can just use this simple function to solve this problem.

JavaScript

Now let’s break it down a little bit.

First I’m using text.split(' '). It converts the sentence into an array of each word.

For example,

"this is an example" became ['this', 'is', 'an', 'example']

Second, I’m using map() to convert each word to be capitalized.

word.charAt(0).toUpperCase() + word.slice(1). This is a simple way to convert a word to be capitalized. It became:

['this', 'is', 'an', 'example']``` to ```['This', 'Is', 'An', 'Example']

And finally I’m just joining each word with a space:

join(' ')

Then it returns "This Is An Example".

Advertisement