Register to get access to free programming courses with interactive exercises

Converting strings into arrays JS: Arrays

At job interviews, they often ask questions like this:

You have a line of text. You need to capitalize the first letter of each word in the text. For simplicity, we'll assume that we're working with a text with no punctuation marks.

const text = 'hello hexlet';
capitalizeWords(text); // 'Hello Hexlet'

There are many ways to solve it. The more methods suggested, the better. These include:

  1. A character-by-character loop through the string.
  2. Converting it into an array.
  3. Using regular expressions. We'll look at these in another course.

Let's break down the solution that involves using an array. To do this, we use the split() method, which splits the string into parts.

const capitalizeWords = (sentence) => {
  // set the separator as space
  const separator = ' ';
  // split the string by the specified separator
  const words = sentence.split(separator);
  // ...
};

The next step is to bypass the resulting array of words and convert the first letter of each word to uppercase. Strings in JavaScript have no built-in method for this, so we'll write one ourselves.

const capitalize = (text) =>
  (text.length === 0) ? text : `${text[0].toUpperCase()}${text.slice(1)}`;

const capitalizeWords = (sentence) => {
  const separator = ' ';
  const words = sentence.split(separator);
  // Forming an array of processed words
  const capitalizedWords = [];
  for (const word of words) {
    capitalizedWords.push(capitalize(word));
  }

  // Combining the processed words back into a sentence
  return capitalizedWords.join(separator);
};

The last action is the inverse of the first. You need to connect the words and return the resulting string.

There's something interesting to note here. The conversion to uppercase occurs not in the words array, but rather in a new one. Why This kind of code makes debugging much easier. If the algorithm does not work correctly, you can always check what's in the words array and what's in the capitalizedWords array. If we changed the words array, then we'd lose this information.


Recommended materials

  1. words function (Lodash)
  2. capitalize function (Lodash)

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY