How to capitalize first letter in JavaScript

In this tutorial, we’re going to look at the different ways of capitalizing the first letter in JavaScript, so let’s get right into it then.

Use String index and the substring method

To start with, let’s use the string index and the substring method.

As you know, strings start from an index of 0 that goes till string_length – 1, as shown in the image below:

So, we can access the character at the 0th index (first character) and use the toUpperCase() method to convert it into upper case if it was in lowercase previously or leave it as it is if it was in upper case already.

Also, the substring method can be used to find the substring of a string with the given positions. So, substring(1) will extract the characters from the 1st index (2nd character) till the end of the string.

The substring method just products a copy though, and so does accessing a string using its index.

So, finally, we can just ‘concatenate’ the capitalized first character and the substring we just extracted and assign the new string back to the original variable ‘str’, as in our example below:

let str = 'hello there, how ARE you?';
str = str.toLowerCase(); //standardize string first 
str = str[0].toUpperCase() + str.substring(1);

As you can see above, we’ve standardized the string first by converting it into lowercase using the toLowerCase method, so in the end, only the first character is capitalized.

You can use the slice method instead of substring too. It works the same.

Use charAt() and slice with toUpperCase()

Instead of accessing the first character using its index, you can use the charAt() method too. It accepts the index of the character you want accessed as its argument (0 in our case).

As I said in the last section, slice works like substring, so in this example, I’ve used slice to slice the string from the 2nd character till the end of the string.

str = str.charAt(0).toUpperCase() + str.slice(1); 

Use regex with the replace() method

You can use regex with replace/match and achieve the same result, without having to slice and concatenate strings.

In regular expressions, ^ indicates the start of the string, and ‘.’ Indicates 1 character. So, together, it means we’re asking for the one character at the start of the string (the 1st character).

We’re replacing this character with str[0].toUpperCase(), meaning, the capitalized first character.

str = str.replace(/^./, str[0].toUpperCase()); 

Use CSS text-transform property and dynamically add class

Alternatively, we can get the help of a CSS property to achieve our results.

CSS has a text-transform property and its ‘capitalize’ value will capitalize the first character of a string, just like we wanted.

To make this example work, let’s create a button of id ‘button’ and a h1 element of id ‘result’ in the index.html file.

<button id="button">Capitalize string</button>
<h1 id="result"></h1> 

Next, let’s set up a class in our style.css file. Let’s call this class capital, and it’ll only have one line of code in it: text-transform: capitalize;

Right now, this class is not assigned to any element, since we’ll dynamically be adding this class to the h1 element from our script file.

.capital {
    text-transform: capitalize;

Now comes the script file. Let’s retrieve both the ‘button’ and ‘result’ elements using the getElementById method. You can use querySelector instead as well.

Then, let’s create the string ‘str’.

When the page is first loaded, we want the original value of str printed out in the h1 tag. We’ll use the innerText property to achieve this.

Then, let’s create a click event listener whose anonymous function will use the className property to add ‘capital’ as the result element’s class.

Now, whenever the user clicks on the button, the h1 reprint the capitalized version of the string because your script file will attach the ‘capital’ class to it.

let button = document.getElementById('button');
let result = document.getElementById('result');

let str = 'hello there, how ARE you?';
result.innerText = str;

button.addEventListener('click', () => {
    result.className = 'capital';

When you run the above lines of code, you’ll see:

Note: This wouldn’t standardize our string (convert the whole string to lowercase before getting started) like we did with the other methods. You can use the toLowerCase() method on str before you assign it to the element though.

Capitalizing the first letter of every word in a string

So far, we’ve been looking at capitalizing only the first character of a string, and we’ve been converting the remaining characters to lowercase beforehand.

What if we want the first character of every word to be capitalized, while the remaining characters remaining in lower case?

We can use loops to achieve that.

Using for loop

In the example below, we’ve used the for loop to capitalize every word of a string. Let’s look at the steps involved in our code:

1. We’ve first split the string by using a single space, ‘ ‘, as the split condition, and we’ve assigned the split array back to str. This way, we now have an array ‘str’ whose elements are the words of the original string.

2. Next, we’ve created a for loop that’ll iterate from 0 till the str.length – 1.

3. Inside the for loop, we’re converting the values inside each str[i], which pertain to every word in the original string to lower case to standardize it first.

4. Then, we’re using charAt(0) and slice(1) conditions as seen before to convert just the first character of the word to upper case.

5. Once the ‘for’ loop finishes iterating, we’ll have an array whose elements contain the words of the original string, but they’ll have capitalized first letters, with the rest of the characters in lower case.

6. Finally, we’ve joined the elements of the array back into a string using the array join method. The join condition is a single space, ‘ ‘, so we get back the original string, but this time, with every first letter of every word capitalized.

let str = 'hello there, how ARE you?';

str = str.split(' ');

for(let i = 0; i < str.length; i++) {
    str[i] = str[i].toLowerCase();
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);

str = str.join(' ');
console.log(str); //Hello There, How Are You? 

Note: You can use while loop to achieve the same result.

Using the map method

JavaScript is an abundant language that offers a lot of pre-defined methods to help solve our problems. This way, we can solve a single problem in multiple ways. Let’s look at one such way by using the map method.

The procedure is quite simple. We’re still splitting and joining strings as before.

But, instead of a loop, we’re using the map method, and for every iteration, we’re creating a temporary element ‘s’ (which will contain one word of the original string) that’ll be standardized (converted to lower case), after which its first letter will be capitalized.

The map method creates a copy of the original array, so you’ll have to reassign it back to ‘str’, as shown below:

let str = 'hello there, how ARE you?';

str = str.split(' ');

str = => {
    s = s.toLowerCase();
    return s[0].toUpperCase() + s.slice(1);

str = str.join(' ');
console.log(str); //Hello There, How Are You? 

That’s it! Those are the 4 ways of capitalizing the first letter of a given string and 2 ways of capitalizing the first character of every word of a string.

Leave a Comment