JS: Arrays
Theory: Converting strings into 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.
There are many ways to solve it. The more methods suggested, the better. These include:
- A character-by-character loop through the string.
- Converting it into an array.
- 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.
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.
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 programs
Completed
0 / 22

