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 π§