Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

Hello

A 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 Smith

Common 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
Hello

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.