In this post we are going to learn how to capitalize first letter of string in Javascript. In Javascript it provides String.toUpperCase() method which capitalizes all letters of a string.
But what if we want to capitalize only first Letter of the String. So we will write our custom function to capitalize only first letter of the string provided.
function capitalize(str) {
if (str && typeof(str) == 'string') {
return str.charAt(0).toUpperCase() + str.slice(1);
}
else {
return null;
}
}
This can be simplified as belows:
function capitalize(str) {
return (str && typeof(str) == 'string') ? str[0].toUpperCase() + str.slice(1) : null;
}
So you can call this method and pass your string and it will return the desired output
Checkout Complete Article here: Capitalize First Letter Javascript