Skip to main content

Capitalize first letter with Javascript

Published ago
Updated ago
5 min read

In this quick tutorial we will learn how to make the first letter of a string uppercase

The easy way

To begin with, why would we need to do this in Javascript? Isn't it easier with CSS? Well, yes, it is easier to do this in CSS, but if for some reason we can't do it that way, we lose nothing by knowing how it's done, but just in case, to do all this in css we only need:

1.test {
2 text-transform: capitalize;
3}
4
Warning

text-transform: capitalize will be applied to all words within the element

In Javascript

To achieve this result using javascript, what we need are 3 steps:

  1. Find the first letter
  2. Convert it to uppercase
  3. Join it with the others

Translated to code it would be something like this:

charAt

charAt( pos ) returns the character that is at the pos (position) indicated, we know that array start at position zero, therefore, to find the first character of our string, we use charAt( 0 ).

1const str = 'foo';
2const firstLetter = str.charAt(0);
3console.log(firstLetter); // f
4

toUpperCase

Now, toUpperCase converts all the characters sent to uppercase, that's why it's important that we first find the first letter, so that it only affects it:

1const str = 'foo';
2const uppercaseStr = str.toUpperCase();
3console.log(uppercaseStr); // FOO
4

slice

slice( start. end ) what it does is cut a string, starting from the character specified in start, and ending at the character specified by end, if end is not specified, it will simply take the total number of characters of the string, reaching the end.

1const str = 'foo';
2const latterStr = str.slice(1);
3console.log(latterStr); // oo
4

Now we have all the necessary parts, we just have to put them together:

1const str = 'foo';
2const firstLetter = str.charAt(0);
3const upperCaseStr = firstLetter.toUpperCase();
4const latterStr = str.slice(1);
5const result = upperCaseStr + latterStr;
6console.log(result); // Foo
7// Short version
8console.log(str.charAt(0).toUpperCase() + str.slice(1)); // Foo
9