How to make the first letter of a String Uppercase in JavaScript
Photo: Mart Production/Pexels
Introduction
In this article, we will learn how to make the first letter of a string uppercase (also known as capitalizing the string). Capitalizing the string helps format user inputs, display names or titles, and enhance the overall presentation of web application text.
Table of Contents
charAt(), toUpperCase() and slice() to the rescue
Let's write a simple solution to capitalize the string using the following JavaScript string methods:
charAt()
charAt() returns the character at the specified index in a string. For example, str.charAt(0) returns the first character of the string str.
toUpperCase()
toUpperCase() converts the entire string to uppercase letters.
slice()
slice() extracts a part of a string and returns it as a new string. For example, str.slice(1) returns the string from the second character to the end of the string.
Step-by-Step Implementation
Now, let's complete our solution for capitalizing the string using the above methods:
- First, we will extract the first character using the charAt() method.
- Then, we will convert the extracted character to uppercase using the toUpperCase() method.
- At last, we will get the remaining string, leaving the first character using the slice() method and concatenating it with the first character that we extracted and converted to uppercase in the first two steps.