Skip to content

How to uppercase the first letter of a string in JavaScript

JavaScript offers many ways to capitalize a string to make the first character uppercase. Learn the various ways, and also find out which one you should use, using plain JavaScript

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;
}
โ†’ Download my free JavaScript Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about js: