Tutorialspoint
Problem
Solution
Submissions

Convert String to Title Case

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

Write a JavaScript program to convert a given string to title case. Title case means the first letter of each word should be uppercase and the rest of the letters should be lowercase. Words are separated by spaces, and you should preserve the original spacing.

Example 1
  • Input: str = "hello world programming"
  • Output: "Hello World Programming"
  • Explanation:
    • The input string has three words: "hello", "world", and "programming".
    • Each word's first letter gets capitalized: "Hello", "World", "Programming".
    • The remaining letters in each word become lowercase.
    • The words are joined back with spaces to form "Hello World Programming".
Example 2
  • Input: str = "javaScript is AWESOME"
  • Output: "Javascript Is Awesome"
  • Explanation:
    • The input string has three words: "javaScript", "is", and "AWESOME".
    • Each word's first letter gets capitalized: "Javascript", "Is", "Awesome".
    • All other letters become lowercase regardless of their original case.
    • The final result is "Javascript Is Awesome".
Constraints
  • 1 ≤ str.length ≤ 1000
  • The string contains only alphabetic characters and spaces
  • There may be multiple consecutive spaces between words
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(n) for the result string
ArraysStringsTech MahindraLTIMindtree
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 an array of words using the space character as delimiter
  • Iterate through each word in the array
  • For each word, convert the first character to uppercase using charAt(0).toUpperCase()
  • Convert the remaining characters to lowercase using substring(1).toLowerCase()
  • Combine the capitalized first character with the lowercase remaining characters
  • Join all the processed words back together with spaces
  • Return the final title case string

Steps to solve by this approach:

 Step 1: Split the input string into an array of words using the space character as the delimiter
 Step 2: Use the map function to iterate through each word in the array
 Step 3: For each word, check if it's not empty to handle multiple consecutive spaces
 Step 4: Extract the first character using charAt(0) and convert it to uppercase
 Step 5: Extract the remaining characters using substring(1) and convert them to lowercase
 Step 6: Concatenate the uppercase first character with the lowercase remaining characters
 Step 7: Join all processed words back together using spaces and return the result

Submitted Code :