Capitalizing first letter of each word JavaScript


In this problem statement, our task is to capitalize the first letters of each word with the help of Javascript functionalities. To solve this problem we need to understand the meaning and logic of the problem.

Understanding the problem statement

The problem statement is to write a function in Javascript that will help to capitalize the first letter of every word in the given string. For example, if we have a string "hello world", the converted version of this string is "Hello World".

Logic for the given problem

For the code we will create a function to do the given task. And inside the function we will use some built in methods of Javascript to modify the string. The function will first split the input string into an array of words and then we will iterate over each word in the array. Inside the loop we will capitalize every first letter of the word and concatenate it with the rest of the word. And lastly join them back together into a string and return the result.

Algorithm

Step 1 − Declare a function called capitalizeWords which is using an argument of string.

Step 2 − Split the words of the given string with the help of split method and put splitted values in words object.

Step 3 − Loop through the words of the string and inside this loop we will capitalize the first letter of each word with the help of toUpperCase method.

Step 4 − And after capitalizing each word we will join them back as a string.

Step 5 − Return the result as capitalized words of the string.

Code for the algorithm

// function for capitalizing the first letter of each words
function capitalizeWords(str) {
   const words = str.split(' ');
   for (let i = 0; i < words.length; i++) {
      const firstLetter = words[i].charAt(0).toUpperCase();
      words[i] = firstLetter + words[i].slice(1);
   }
   return words.join(' ');
}
const inputString = "hello tutorials point, i am learning javascript";
const capitalizedString = capitalizeWords(inputString);
console.log(capitalizedString);

Complexity

The time taken by the function is O(n) because the method uses a constant time to work for every word in the given string. And n is the size of the given string. And the space used by the code is also O(n) as it is storing the result as only the first capitalized word of the string.

Conclusion

So the above created function can be used to capitalize the first letter of every word with the time complexity O(n). We have basically used some built-in methods of Javascript to solve the given problem.

Updated on: 18-May-2023

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements