JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to capitalize the first letter of a string in JavaScript?

To capitalize the first letter of a string, you need to go through the following steps:

  1. First of all, you need to get the character at the 0th index position. To do this, call the charAt() method.
  2. Then, call the toUpperCase() method to convert the letter to uppercase.
  3. After that, using the slice() method, get the substring from the 1st index position to the end of a string.
  4. Finally, concatenate the uppercase letter obtained in step 2 with the substring returned by the slice() method in step 3.

In this way, you can capitalize the first letter of a string.

let str = "doughnut";
str = str.charAt(0).toUpperCase() + str.slice(1);
console.log(str); //Doughnut

The charAt() method returns a character at the index position passed to it. In this case, we want the character at the 0th position; that is why we passed 0 to it.

let str = "doughnut";
console.log(`First character: ${str.charAt(0)}`); //d
console.log(`Second character: ${str.charAt(1)}`); //o
console.log(`Last character: ${str.charAt(str.length - 1)}`); //t

The toUpperCase() method converts all the letters in a string to uppercase.

The slice() method is used to extract a part of a string. In this example, we need substring from the 1st index position to the end of a string; that is why we passed 1 as the startIndex.

When you don't specify the endIndex, the slice() method goes till the end of the string.

You might find a situation where you need to capitalize the first letter of each word in a string. To achieve this, you need to extract individual words from the string by calling the split() method.

Once you have all the words, call the array map() method to iterate through the array. Within the callback function of the map() method, call the charAt() method to get the first letter and then, using the toUpperCase() method, convert it to uppercase.

After that, extract the substring with the help of the slice() method. Finally, merge the uppercase letter with the substring.

let str = "electric vehicles are the future of transportation.";

let arr = str.split(" ");

const newArr = arr.map(element => element.charAt(0).toUpperCase() + element.slice(1));
console.log(newArr); //["Electric", "Vehicles", "Are", "The", "Future", "Of", "Transportation."]

str = newArr.join(" ");
console.log(str); //"Electric Vehicles Are The Future Of Transportation."

Recommended Posts