How to Convert the First Letter of a String to Uppercase in JavaScript

08/01/2021

Contents

In this article, you will learn how to convert the first letter of a string to uppercase in JavaScript.

Converting the first letter of a string to uppercase in JavaScript

In JavaScript, you can convert the first letter of a string to uppercase using different methods.

Using the toUpperCase() and charAt() methods

You can use the toUpperCase() method to convert a character to uppercase and the charAt() method to get the first character of a string. By combining these methods, you can convert the first letter of a string to uppercase.

Example

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

In this example, we converted the first letter of the original string “hello, world!” to uppercase by combining the toUpperCase() and charAt() methods.

Using the replace() method with a regular expression

You can also use the replace() method with a regular expression to replace the first letter of a string with its uppercase equivalent. The regular expression /^[a-z]/ matches the first lowercase letter of the string.

Example

const str = "hello, world!";
const result = str.replace(/^[a-z]/, (match) => match.toUpperCase());
console.log(result); // "Hello, world!"

In this example, we converted the first letter of the original string “hello, world!” to uppercase by using the replace() method with a regular expression.