How to Make the First Letter of String Uppercase in Javascript?

javascript

There are several ways to make the first letter of a string uppercase in Javascript. Here are three common methods:

  1. 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"
  1. 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"
  1. 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.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?