How to Make the First Letter of String Uppercase in Javascript?
There are several ways to make the first letter of a string uppercase in Javascript. Here are three common methods:
- Using the toUpperCase() and slice() Methods
This method involves using the toUpperCase() method to convert the first letter of the string to uppercase, and the slice() method to extract the rest of the string:
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
capitalizeFirstLetter("hello world"); // returns "Hello world"
- Using Regular Expressions and the replace() Method
This method involves using a regular expression to match the first letter of the string, and the replace() method to replace it with the uppercase version:
function capitalizeFirstLetter(str) {
return str.replace(/^\w/, c => c.toUpperCase());
}
capitalizeFirstLetter("hello world"); // returns "Hello world"
- Using ES6 Template Literals
This method uses ES6 template literals, which allow for variable interpolation, to concatenate the uppercase first letter with the rest of the string:
function capitalizeFirstLetter(str) {
return `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
}
capitalizeFirstLetter("hello world"); // returns "Hello world"
All three methods achieve the same result of making the first letter of a string uppercase in Javascript.