How to capitalize the first letter of a string
Short answer
There is no built-in method. Uppercase the first letter and append the rest of the string:
const text = 'hello';
console.log(text[0].toUpperCase() + text.slice(1));Output:
HelloA helper function
The empty-string check avoids reading a character that does not exist:
function capitalize(text) {
if (text === '') {
return text;
}
return text[0].toUpperCase() + text.slice(1);
}
console.log(capitalize('hello world'));
console.log('[' + capitalize('') + ']');Output:
Hello world
[]Every word
Split the string into words, process each one and join them back:
const title = 'john smith'
.split(' ')
.map((word) => word[0].toUpperCase() + word.slice(1))
.join(' ');
console.log(title);Output:
John SmithCommon mistake
The rest of the string keeps its case. If the input may be in capitals, convert the rest to lowercase first:
const text = 'hELLO';
console.log(text[0].toUpperCase() + text.slice(1));
console.log(text[0].toUpperCase() + text.slice(1).toLowerCase());Output:
HELLO
HelloFunctions used in this recipe
- String.prototype.toUpperCase — Converts a string to uppercase.
- String.prototype.slice — Returns part of a string.
- String.prototype.toLowerCase — Converts a string to lowercase.