How to capitalize the first letter of a string in JavaScript

JavaScript provides a variety of ways to capitalize a string so that the first character becomes uppercase. Learn various methods and use normal JavaScript to find out which method should be used

One of the most common operations on strings is to capitalize the string: capitalize its first letter and leave the rest as it is.

The best way is to combine the two functions. Cut the first letter in a capital, the second into a string, and return from the second character:

const name = 'flavio'
const nameCapitalized = name.charAt(0).toUpperCase() + name.slice(1)

You can extract it into a function that also checks whether the passed parameter is a string, and if not, it returns an empty string:

const capitalize = (s) => {
  if (typeof s !== 'string') return ''
  return s.charAt(0).toUpperCase() + s.slice(1)

capitalize(‘flavio’) //‘Flavio’ capitalize(‘f’) //‘F’ capitalize(0) //’’ capitalize({}) //’’

Instead of usings.charAt(0)You can also use string index (older IE version does not support):s[0].

Some solutions online advocate adding functions to the String prototype:

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1)

(We use regular functions to take advantage ofthis-Arrow functionIt will fail in this case becausethisThe arrow function does not refer to the current object)

This solution is not ideal because it is generally not recommended to edit prototypes, and it is much slower than a solution with independent functions.

Don’t forget, if you just want to capitalize on a web page for presentation, CSS may be a better solution, just add onecapitalizeClass into your HTML paragraph and use:

p.capitalize {
  text-transform: capitalize;

Download mine for freeJavaScript beginner's manual

More js tutorials: