In this tutorial, we will see how to Capitalize first letter in Javascript.
Table of Contents
Capitalize first letter of String in Javascript
There are multiple ways to Capitalize first letter of String in Javascript. Let’s go through each of them.
Using charAt(), toUpperCase() and slice()
We will combination of charAt()
, toUpperCase()
and slice()
functions to capitalize first letter in Javascript.
1 2 3 4 5 |
const str = 'java2blog'; const capitalizeStr = str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalizeStr); |
Output:
Let’s see how it works by going through each method used to capitalize first letter in Javascript.
charAt()
charAt() method returns character at given index in String.
Syntax
1 2 3 |
const chr = str.charAt(index); |
Since we have to capitalize first letter here, we will use str.charAt(0)
to extract first letter from the String.
1 2 3 4 5 |
const str = 'java2blog'; const firstChar = str.charAt(0); console.log(firstChar); |
Output:
toUpperCase()
toUpperCase() function returns all input character in uppercase.
Syntax
1 2 3 |
const upperCaseStr = str.toUpperCase(); |
Since we have to convert first letter to upper case here, we will use str.toUpperCase().
1 2 3 4 5 |
const str = 'java2blog'; const upperCaseStr = str.toUpperCase(); console.log(firstChar); |
Output:
slice()
slice() function returns substring from provided start index until the provided end index.
Syntax
1 2 3 |
const substr = string.slice(start, end) |
If you don’t provide end index, then it will by default returns substring upto end of the String.
1 2 3 4 5 |
const str = 'java2blog'; const substr = str.slice(1); console.log(substr); |
Output:
So we have used str.charAt(0)
to extract first letter of String, str.toUpperCase()
to capitalize first letter of String and str.slice(1)
to concatenate remaining string to the result.
1 2 3 |
const capitalizeStr = str.charAt(0).toUpperCase() + str.slice(1); |
Capitalize each word of String in Javascript
We will now capitalize each word of sentence in Javascript. To do this, we will first split the string into multiple words and store it in array. Iterate over array to apply above capitalize first letter concept to each word and then join them back to form result String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const str = 'how are you doing'; // Split the array on the basis of blank space const strArr = str.split(" "); //iterate through each element of the array and capitalize the first letter of word. for (var i = 0; i < strArr.length; i++) { strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1); } // Join all the array elements with space to form sentence again const capitalizeWordsStr = strArr.join(" "); console.log(capitalizeWordsStr); |
Output:
That’s all about how to Capitalize first letter in Javascript.