Capitalize the first letter of a String in JavaScript

In this post we are going to create a function that accepts a string as an argument and returns the string with capitalized first letter.

Steps to achieve it

Get the first letter

There are two ways to get the first letter from the string

const str = 'hello dev';

console.log(str[0]); // 'h'
console.log(str.charAt(0)); // 'h'

Here, out of the above to methods I use charAt() method because for any index out of the range it returns empty string where as [0] might return undefined if stris ''. and this may cause error when we try to execute toUpperCase method in the next step.

const str = '';

console.log(str[0]); // undefined
console.log(str.charAt(0)); // ''

Capitalize the first letter

To capitalize the first letter, we use the built-in method of JavaScript.

console.log('Utopia'.toUpperCase()); // UTOPIA

Adding the capitalized letter to remaining string

After capitalizing the first letter we need to add it to the original string, but remove the first letter from original string before adding the capitalized letter.

So to get the remaining string, we use the slice method on the string (you can also use substring)

console.log('hello'.slice(1)); // 'ello'

Creating a reusable function

Using the above steps, let create a function to capitalize the first letter of any string passed to it.

function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);

capitalizeFirstLetter('hello dev'); // "Hello dev"

Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →