Capitalize the First Letter of String in TypeScript

While working on a user form in a TypeScript application, I had to ensure that the string values, such as name and email, should be stored in Title case, also known as Proper case (Adam Smith). In the form, the user might enter the details in lowercase, and to ensure consistent capitalization, it was required to convert the input to Proper case.

In this tutorial, I will explain how to capitalize the first letter of a string in TypeScript. With this, you will be able to format user input, such as names or addresses, to ensure consistent capitalization.

Using the slice() and toUpperCase() Methods

One of the simplest ways to capitalize the first letter of a string in JavaScript is by using the slice() and toUpperCase() methods together. Here’s an example:

function capitalizeFirstLetter(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

const userName = "john";
console.log(capitalizeFirstLetter(userName));  // Output: "John"

Output:

Capitalize string in TypeScript

In this example, we define a function called capitalizeFirstLetter that takes a string parameter str. Inside the function, we use str.charAt(0) to get the first character of the string and then apply the toUpperCase() method to convert it to uppercase.

Finally, we concatenate the capitalized first letter with the rest of the string using str.slice(1), which returns a new string starting from the second character.

Check out: Remove Spaces from a String in TypeScript

Capitalizing Multiple Words

If you have a string with multiple words and want to capitalize the first letter of each word, you can use the split(), map(), and join() methods in combination with the previous approach. Here’s how you can do it:

function capitalizeFirstLetter(word: string): string {
  return word.charAt(0).toUpperCase() + word.slice(1);
}

function capitalizeWords(str: string): string {
  return str.split(" ").map(word => capitalizeFirstLetter(word)).join(" ");
}

const address = "123 main street, new york";
console.log(capitalizeWords(address)); // Output: "123 Main Street, New York"

Output:

TypeScript Capitalize Strings

In this example, the capitalizeWords function takes a string str and splits it into an array of words using str.split(” “). Then, we use map() to apply the capitalizeFirstLetter function to each word, capitalizing the first letter of each word. Finally, we join the array of capitalized words back into a string using join(” “).

Check out: Convert Boolean to String in TypeScript

Handling Edge Cases

When dealing with user input, it’s important to handle edge cases gracefully. Consider the following scenarios:

Empty Strings

If the input string is empty, you might want to return an empty string or handle it according to your application’s requirements. Here’s an example:

function capitalizeFirstLetter(str: string): string {
  if (str === "") {
    return "";
  }
  return str.charAt(0).toUpperCase() + str.slice(1);
}

const emptyString = "";
console.log(capitalizeFirstLetter(emptyString)); // Output: ""

String with Leading Spaces

If the input string contains leading spaces, you might want to trim the string before capitalizing the first letter. Here’s how you can modify the capitalizeFirstLetter function:

function capitalizeFirstLetter(str: string): string {
  const trimmedStr = str.trim();
  return trimmedStr.charAt(0).toUpperCase() + trimmedStr.slice(1);
}
const nameWithSpaces = "john";
console.log(capitalizeFirstLetter(nameWithSpaces)); // Output: "John"

Output:

Capitalize first letter of string in TypeScript

In this example, we use the trim() method to remove any leading or trailing whitespace from the string before capitalizing the first letter.

Check out: Generate Random Strings in TypeScript

Using CSS for Capitalization

If you’re working with HTML and CSS, you can also achieve capitalization using CSS text transformations. Here’s an example:

<style>
  .capitalize {
    text-transform: capitalize;
  }
</style>

<p class="capitalize">john doe</p>

In this case, applying the CSS class capitalize to an element will capitalize the first letter of each word within that element.

Check out: Convert a String to Lowercase in TypeScript

Performance Considerations

When working with large datasets or frequently capitalizing strings, performance can be a concern. Here are a few tips to optimize your code:

  • Use built-in methods like charAt(), slice(), and toUpperCase() instead of custom implementations.
  • Avoid unnecessary function calls or string manipulations.
  • Consider caching the results if you need to capitalize the same strings multiple times.

Conclusion

In this TypeScript tutorial, we have learned various methods to capitalize the first letter of a string in TypeScript. Whether you’re working with user input, formatting names, or addressing edge cases, these methods will help to convert a lowercase string to Proper case.

While using the above methods, remember to handle empty strings, trim leading spaces, and consider performance optimizations for large datasets.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.