How to capitalize the first letter of a string in JavaScript

In JavaScript, we can use the built-in String.toUpperCase method to capitalize all letters of a string. In our case, however, we want to capitalize only the first letter while keeping the rest as they are.

To achieve this, we can split the input string into two substrings, where the first substring contains only the first character, while the second contains the rest of the string. We can then use the toUpperCase method on the first substring and append the second substring to it.

Syntax

The toUpperCase method follows the below syntax. It is called by a string, and it returns the modified string. This method doesn't change the original string; instead, it creates a copy.

string.toUpperCase()
Syntax of toUpperCase() method

Code

The code below implements the solution discussed above:

let text = "educative";
let capitalized = text.charAt(0).toUpperCase() + text.slice(1);
console.log(capitalized);

In the code above, we implement the following:

  • Line 1: We define a variable called text to act as our input string.

  • Line 2: We use the charAt method to retrieve the first letter of the input string and capitalize it using the toUpperCase method. We use the slice method to retrieve the rest of the string—excluding the first letter—and append it to the capitalized first letter.

  • Line 3: We print the result to the console.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved