How to capitalize first letter - JavaScript

Mo Ibra

Mo Ibra

Dec 22, 2022

In this article we will learn how capitalize first letter of a string.

It is very common capitalize first letter of a string in JavaScript.


Problem

Now we have a problem, which is that we want to capitalize the first letter of the word, and this can happen a lot in the world of programming.

Now let's imagine we have a string like this:

"hello world"

And we want to capitalize the first character for some reason, so that the string becomes like this:

"Hello world"

How to solve this problem?

You think the problem is easy, right? But in fact, it is not very easy because there is no function that capitalizes only the first character in the string in JavaScript.

So we will make a solution by ourselves.

The solution will be as follows

  • Use the charAt(0) method to get first letter
  • We will capitalize first letter with toUppercase() method
  • Use the slice(1) method to slice the string leaving the first character.
  • Finally, We will concatenate the output of both functions.

Solution:

Before writing the full code, I will write line by line so that you understand exactly what is happening.

First we have to get the first letter to be capitalized, right?

// String
const string = "hello world";

// Get First Letter
const first = string.charAt(0);

// Result:
console.log(first);

Output

h

Now let's capitalize that letter

// String
const string = "hello world";

// Get First Letter
const first = string.charAt(0);

// Capitalize first letter
const capitalFirst = first.toUpperCase();

// Result:
console.log(capitalFirst);

Output

H

Now we get the string starting from the second letter to the end.

// String
const string = "hello world";

// Get First Letter
const first = string.charAt(0);

// Capitalize first letter
const capitalFirst = first.toUpperCase();

// Rest of string
const rest = string.slice(1);

// Result
console.log(rest);

Output

ello world

Now we will concatenate uppercase letter with rest of string.

Full code

// String
const string = "hello world";

// First letter
const first = string.charAt(0);

// Capitalize first letter
const capitalFirst = first.toUpperCase();

// Rest of string
const rest = string.slice(1);

// Concatenation
const result = capitalFirst + rest;

// Result:
console.log(result);

Output

Hello world

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: