Introduction
There are countless coding challenges available in every programming language that help us develop algorithmic thinking. Moreover, by solving these challenges, we gain valuable insight into how to approach problem-solving when we encounter difficulties during coding. One such challenge is known as Title Case A String, where the goal is to capitalize the first letter of each word in a sentence. For example, given the string I'm very hungry for coding, our task is to convert it to I'm Very Hungry For Coding. Do you understand how the output should look? There are several approaches to solving this challenge, and in this tutorial, I will demonstrate one way to solve it.
Using for loop:
In this method, I used a for loop to iterate over the entire string, which allows me to work with each word individually. This is a widely used and effective method in almost every programming language.
function titleCase(str) {
let strToLower = str.toLowerCase();
let strToArray = strToLower.split(' ');
let strFirstCharArray = [];
for(let i = 0; i < strToArray.length; i+=1) {
strFirstCharArray.push(strToArray[i][0].toUpperCase() + strToArray[i].slice(1));
}
return strFirstCharArray.join(' ');
}
console.log(titleCase("i'm very hungry for coding"));
// output = I'm Very Hungry For Coding
I know you might have many questions. Don't worry; I will help you understand everything by breaking the code into small pieces, as I did above. Let's get started
Breaking Up Solution:
First, I declared a string let str = "I'm very hungry for coding";. Now, we have to convert this into a title case.
We then need to convert the string to lowercase to ensure that no uppercase letters are retained in the middle of the string, as in I’m veRy huNgrY fOr CodIng. If we do not take this step now, we may face issues later. To do this, I declared a new variable: let strToLower = str.toLowerCase();. Remember, this will convert the entire string to lowercase.
In the next step, we need to convert the string into an array, which will be helpful for accessing the first letter of each word when starting a loop. I used the JavaScript built-in method split(' ') to convert it into an array.
Note: Make sure to include a space between the quotation marks in split(' '). If you forget to add a space, the output will be different and could cause a problem.
After that, I declared a new empty array, let strFirstCharArray = [];, where I will push my final text (the sentence converted into Title Case) after the loop. Then, I started a loop. Inside the loop, I added this code: strFirstCharArray.push(strToArray[i][0].toUpperCase() + strToArray[i].slice(1));
Explanation:
- strFirstCharArray.push adds the final values to the array.
- strToArray[i][0] provides us with each word's first character.
- toUpperCase() converts all these characters into capital letters.
- + strToArray[i].slice(1) combines the rest of each word's characters by omitting the first characters of each word.