Skip to main content

Converting a String to Title Case using JavaScript

Overview

Converting strings to title case (where the first letter of each word is capitalized) is frequently needed in JavaScript, especially for displaying text in user interfaces or preparing data for reports. This snippet provides a simple and effective way to transform any given string into title case.

Code

Title Case Conversion Function

function toTitleCase(str) {
return str
.toLowerCase()
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.substring(1))
.join(" ");
}

Example Usage

Converting a String to Title Case

const sentence = "welcome to the world of JavaScript";
const titleCaseSentence = toTitleCase(sentence);
console.log("Title Case:", titleCaseSentence);

Code Description

The toTitleCase function is an efficient way to convert a string to title case:

  • Purpose: To capitalize the first letter of each word in a string, converting the rest of each word to lowercase.
  • Implementation: First, converts the entire string to lowercase. Then, splits the string into words, capitalizes the first character of each word, and joins them back into a single string.
  • Return Value: A new string where each word starts with an uppercase letter and the remaining characters are lowercase.

This function is useful for text formatting in web applications, such as formatting names, titles, or headers.

References