JavaScript code to make the first letter of a string uppercase


You can make the first letter of a string uppercase in JavaScript by using either of the following methods:

Using string concatenation and toUpperCase() method

function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

Using replace() method and regular expression:

function capitalizeFirstLetter(str) {
return str.replace(/^\w/, (c) => c.toUpperCase());
}

Both of these methods work by taking the first character of the string and converting it to uppercase, then concatenating it with the rest of the string (in the first method) or using replace() method to replace the first character with its uppercase equivalent (in the second method).

Here’s an example usage:

const str = "hello world";
const capitalizedStr = capitalizeFirstLetter(str);
console.log(capitalizedStr); // "Hello world"