Tutorialspoint
Problem
Solution
Submissions

Capitalize First Letter of Each Word

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript function to capitalize the first letter of each word in a given string. The function should convert the first character of every word to uppercase while keeping the rest of the characters in their original case.

Example 1
  • Input: str = "hello world programming"
  • Output: "Hello World Programming"
  • Explanation:
    • The input string contains three words: "hello", "world", "programming".
    • First letter of "hello" becomes "H", making it "Hello".
    • First letter of "world" becomes "W", making it "World".
    • First letter of "programming" becomes "P", making it "Programming".
    • The final result is "Hello World Programming".
Example 2
  • Input: str = "javascript is awesome"
  • Output: "Javascript Is Awesome"
  • Explanation:
    • The input string contains three words: "javascript", "is", "awesome".
    • First letter of "javascript" becomes "J", making it "Javascript".
    • First letter of "is" becomes "I", making it "Is".
    • First letter of "awesome" becomes "A", making it "Awesome".
    • The final result is "Javascript Is Awesome".
Constraints
  • 1 ≤ str.length ≤ 1000
  • The string may contain multiple spaces between words
  • Words are separated by spaces
  • Time Complexity: O(n) where n is the length of string
  • Space Complexity: O(n) for the result string
ArraysStringsEYTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Split the string into individual words using space as delimiter
  • Iterate through each word in the array
  • For each word, capitalize the first character using toUpperCase()
  • Keep the rest of the characters as they are using substring()
  • Join all the processed words back with spaces
  • Handle edge cases like empty strings or single characters

Steps to solve by this approach:

 Step 1: Split the input string into an array of words using space as delimiter.
 Step 2: Use the map() method to transform each word in the array.
 Step 3: For each word, check if it's not empty to avoid errors.
 Step 4: Use charAt(0).toUpperCase() to capitalize the first character.
 Step 5: Use slice(1) to get the remaining characters of the word.
 Step 6: Concatenate the capitalized first character with the remaining characters.
 Step 7: Join all transformed words back into a single string with spaces.

Submitted Code :