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.

titleCase("this is an example") // Should return "This Is An Example"

titleCase("test") // Should return "Test"

titleCase("i r cool") // Should return "I R Cool"

titleCase("WHAT HAPPENS HERE") // Should return "What Happens Here"

titleCase("") // Should return ""

titleCase("A") // Should return "A"

This is the code I’ve tried:

const titleCase = function(text) {
  text = text.split(' ');

  for (let i = 0; i < text.length; i++) {
    text[i] = text[i].toLowerCase().split('');
    text[i][0] = text[i][0].toUpperCase();
    text[i] = text[i].join('');
  }

  if (text === "") {
    return ""
  }

  return text.join(' ');
}

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

Advertisement

Answer

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

function titleCase(text) {
    return text.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
}

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