Capitalize first letter in Javascript

June 28, 2020

#Javascript

There are many solutions to capitalize the first letter in Javascript and today I’m going to bring you my own.

The idea πŸ’‘

We can consider the final string as the addition of the first string character capitalized and the remaining part.
If we take for example the word β€œchuck”, our transform operation steps are:

  • Take the first character and uppercase it: chuck => C
  • Take the remaining part: chuck => huck
  • Build the final result: C + huck => Chuck

The code ⌨️

let string = 'Chuck';

let firstLetter = string.charAt(0).toUpperCase();
let remainingPart = string.slice(1);
let result = firstLetter + remainingPart;

console.log(result); // Chuck
Compact mode function
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

console.log(capitalize('chuck')); // Chuck

This is just one of the solutions, you can take it as is or find out your own! πŸ˜ƒ

Hope you enjoy this post,

Pingu 🐧


Written by Pingu who lives and works in Genoa building useful modern applications.

Something to share ?