Converting Text to Title Case with JavaScript

1 min read .

Converting text to title case can enhance readability and aesthetics, especially for titles or names. Title case is a format where each word in a title starts with a capital letter, except for certain words that are usually not capitalized. How to create a JavaScript function to convert text to title case.

The titleCase Function

Here is the implementation of the titleCase function that converts text to title case:

function titleCase(string) {
    let sentence = string.toLowerCase().split(" ");
    for (var i = 0; i < sentence.length; i++) {
        sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
    }

    return sentence.join(" ");
}

Code Explanation

  1. Convert Text to Lowercase and Split into Array:

    let sentence = string.toLowerCase().split(" ");
    • string.toLowerCase() converts the entire string to lowercase to ensure consistency when modifying each word.
    • split(" ") splits the string into an array based on spaces. Each element of the array is a word from the original string.
  2. Convert Each Word to Title Case:

    for (var i = 0; i < sentence.length; i++) {
        sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
    }
    • A for loop is used to iterate through each word in the array.
    • sentence[i][0].toUpperCase() converts the first letter of the word to uppercase.
    • sentence[i].slice(1) gets the rest of the word after the first letter.
    • sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1) combines the capitalized first letter with the rest of the word that has been converted to lowercase.
  3. Join Array Back into String:

    return sentence.join(" ");
    • sentence.join(" ") combines the array elements back into a string with spaces as separators.

Example Usage

Here are some examples of using the titleCase function:

console.log(titleCase("hello world")); // Output: "Hello World"
console.log(titleCase("javascript is awesome")); // Output: "Javascript Is Awesome"
console.log(titleCase("title case conversion")); // Output: "Title Case Conversion"
  • Example 1: "hello world" is converted to "Hello World".
  • Example 2: "javascript is awesome" is converted to "Javascript Is Awesome".
  • Example 3: "title case conversion" is converted to "Title Case Conversion".

Conclusion

The titleCase function is a simple yet effective tool for converting text to title case. By using JavaScript built-in methods such as toLowerCase, split, toUpperCase, and join, this function provides an easy way to format text consistently. It is particularly useful for creating titles, labels, or other text that requires a clean and structured format.

Understanding how this function works allows you to easily customize and implement it in your projects to enhance text readability and presentation.

See Also

chevron-up