How to change the first letter of a string to uppercase in Javascript


I'm trying to change the first letter of a string to uppercase, toUpperCase() method changes whole string to uppercase. How can I change the first letter alone to uppercase?

1 Answer

5 years ago by

This is one of the generic requirement where you need to change the first letter alone to uppercase. You can choose any of the following methods to change the first character alone to uppercase.

str = "onecompiler";

console.log(str[0].toUpperCase() + str.slice(1)); //method: 1

console.log(str.charAt(0).toUpperCase() + str.slice(1)); //method: 2

console.log(str.replace(/^./, str[0].toUpperCase())); //method: 3
5 years ago by Divya