How to Capitalize first letter in Javascript

Javascript capitalize first letter

In this tutorial, we will see how to Capitalize first letter in Javascript.

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.

Output:

Java2blog

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

Since we have to capitalize first letter here, we will use str.charAt(0) to extract first letter from the String.

Output:

J

toUpperCase()

toUpperCase() function returns all input character in uppercase.
Syntax

Since we have to convert first letter to upper case here, we will use str.toUpperCase().

Output:

JAVA2BLOG

slice()

slice() function returns substring from provided start index until the provided end index.
Syntax

If you don’t provide end index, then it will by default returns substring upto end of the String.

Output:

ava2blog

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.

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.

Output:

How Are You Doing

That’s all about how to Capitalize first letter in Javascript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *