Capitalizing a string means uppercasing the first letter of it. It’s one of the most common operations with strings in JavaScript: uppercase its first letter, and leave the rest of the string as-is.

The best way to make the first character uppercase is through a combination of two functions.

One function is used to to uppercases the first letter, and the second function slices the string and returns it starting from the second character.

Like this:

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


You can extract that method of capitalizing a string to a function, which also checks if the passed parameter is a string, and returns an empty string if not:

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 using s.charAt(0) you could also use string indexing (not supported in older IE versions): s[0].

Some solutions online to do the same capilization by having the first letter uppercase advocate for adding the function to the String prototype:

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


(we use a regular function to make use of this - arrow functions would fail in this case, as this in arrow functions does not reference the current object)

This solution is not ideal, because editing the prototype is not generally recommended, and it’s a much slower solution than having an independent function.

Don’t forget that if you just want to capitalize (having the first letter uppercase) for presentational purposes on a Web Page, CSS might be a better solution, just add a capitalize class to your HTML paragraph and use:

p.capitalize {
text-transform: capitalize;
}


If you like videos, I also made a video on how to uppercase the first letter of a string in JavaScript: