How to capitalize the first letter in JavaScript

The utility function below should do the capitalization of the first letter. But if you are dealing with internationalization you may need to find better alternatives.

function capitalizeFirstLetter(string) {
  return string.slice(0, 1).toUpperCase() + string.slice(1);
}

capitalizeFirstLetter('hey'); // returns 'Hey'

How does it work?

  1. The string.slice(0, 1) code extracts the first character.
  2. The .toUpperCase() converts the first character to upper case.
  3. The string.slice(1) returns the initial string except the first character.
  4. Everything is concatenated with the + operator.

You could also do string.chartAt(0) instead of string.slice(0,1).

Questions

What's the function f output?

function f(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

f('hello');

What's the function f output?

function f(string) {
  return string.slice(0, 1).toUpperCase() + string.slice(1);
}

f('hello');