How to Capitalize the First Letter of a String in JavaScript
How can we capitalize just the first letter of a string?
CSS gives us the ability to apply text-transform: capitalize;
to DOM text elements, but what if we need to capitalize strings in JavaScript?
Given a string s
, we would first need to obtain the first letter of the string.
let s = "corgi";
s.charAt(0); // 'c'
And then capitalize that letter.
s.charAt(0).toUpperCase(); // 'C'
We then need to obtain the rest of the word.
s.slice(1); // 'orgi'
And then tack it on.
s.charAt(0).toUpperCase() + s.slice(1); // 'Corgi'
Let’s put this all together into a function. We’ll also add an extra check for non-string types.
const cap = (s) => {
if (typeof s !== "string") return "";
return s.charAt(0).toUpperCase() + s.slice(1);
};
cap('corgi'); // 'Corgi'
cap('shih tzu'); // 'Shih tzu'
cap(''); // ''
We can also add this function to the String prototype.
String.prototype.cap = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
'corgi'.cap() // 'Corgi'
'shih tzu'.cap() // 'Shih tzu'
''.cap() // ''