How Do I Make the First Letter of a String Uppercase in JavaScript

As a JavaScript developer, it’s common to come across situations where you need to modify the case of a string, such as making the first letter uppercase.

Fortunately, JavaScript provides several ways to achieve this, and in this post, we will explore the different methods you can use to make the first letter of a string uppercase.


Method 1: Using the toUpperCase() and slice() methods

One of the simplest ways to make the first letter of a string uppercase in JavaScript is to combine the toUpperCase() and slice() methods.

The toUpperCase() method converts all the characters in a string to uppercase, while the slice() method extracts a section of a string and returns it as a new string.

Here is an example:

const str = "hello world";
const capitalizedStr = str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalizedStr); // "Hello world"

In the above example, we first use the charAt() method to get the first character of the string, then use the toUpperCase() method to convert it to uppercase.

We then concatenate the uppercase first letter with the rest of the string, which we get using the slice() method.

Method 2: Using the substring() method

Another way to make the first letter of a string uppercase is to use the substring() method.

This method extracts the characters of a string between two specified indices and returns the new string.

Here is an example:

const str = "hello world";
const capitalizedStr = str.substring(0, 1).toUpperCase() + str.substring(1);
console.log(capitalizedStr); // "Hello world"

In this example, we use the substring() method to extract the first character of the string, then use the toUpperCase() method to convert it to uppercase.

We then concatenate the uppercase first letter with the rest of the string, which we get using another call to the substring() method, this time starting from the second character.

Method 3: Using Regular Expressions

Regular expressions are a powerful tool in JavaScript, and you can use them to make the first letter of a string uppercase.

Here is an example:

const str = "hello world";
const capitalizedStr = str.replace(/^\w/, (c) => c.toUpperCase());
console.log(capitalizedStr); // "Hello world"

In this example, we use the replace() method to find the first word character in the string (which is the first letter) using the regular expression ^\w, which matches the start of the string (^) followed by a word character (\w).

We then use an arrow function to pass the matched character to the toUpperCase() method, which converts it to uppercase.

The replace() method then replaces the matched character with the uppercase version.


Conclusion

In conclusion, we have explored three different methods you can use to make the first letter of a string uppercase in JavaScript.

Each method has its advantages and disadvantages, so you can choose the one that best suits your needs.