Explain Codes LogoExplain Codes Logo

How do I make the first letter of a string uppercase in JavaScript?

javascript
string-manipulation
browser-compatibility
performance
Alex KataevbyAlex Kataev·Aug 11, 2024
TLDR

Here's your quick fix to make the first letter of a string uppercase in JavaScript:

const capitalize = (str) => str && str.charAt(0).toUpperCase() + str.slice(1);

This tight piece of code takes care of transforming the first letter—if it's a letter—into uppercase. All while leaving the rest of the string untouched. To see it in action:

console.log(capitalize('hello')); // Outputs: 'Hello'

Pro tips and tricks

Beyond the basic capitalization, dealing with different scenarios and edge cases can make your code more resilient and versatile.

Tackling empties and nulls

Always ensure the string is neither empty nor null before proceeding:

const reliableCapitalize = (str) => str ? str.charAt(0).toUpperCase() + str.slice(1) : '';

Why use it? With this function, you're guaranteed to get a string, even if the input is null or an empty string (''). Yup, no unpleasant surprises here!

Keeping compatibility with older browsers

Older browsers like IE7 might give you a cold shoulder if you use bracket notation (string[0]). To avert any silent treatments from these folks, using charAt(0) is recommended. Now, that's classic!

Avoiding script clash with prototype extensions

Extending String.prototype can lead to cut-throat contest with other scripts or libraries. If you must extend, consider using Object.defineProperty to do so in a non-enumerable manner:

Object.defineProperty(String.prototype, 'capitalize', { value: function() { return this.charAt(0).toUpperCase() + this.slice(1); }, enumerable: false });

Prototypes can get messy. Clean up with non-enumerable properties!

Kissing regex goodbye for performance

Regex can be fun but also tends to be slower compared to charAt and slice methods. In these simple conditions, stick to what works faster, because time is money!

Going the extra mile

Capitalization isn't always a walk in the park. Here are the answers to those "But what if…" questions that you may have.

Dealing with non-letter characters

Your string might even begin with a non-alphabetic character. A simple regex test before proceeding is all it takes:

const bulletproofCapitalize = (str) => /^[a-zA-Z]/.test(str) ? capitalize(str) : str;

Guess we just made the function 'bulletproof'. Suit up!

Working with sentences

Ever wanted to capitalize the first letter of each word in a string? Here you go:

const capitalizeSentence = (str) => str.replace(/\b\w/g, m => m.toUpperCase());

Making sentences more mannered, one word at a time!

Looking fancy with CSS

Sometimes, it's not the data but how it’s shown. Using CSS, you can make the first letter look capitalized:

p::first-letter { text-transform: capitalize; }

Maintaining data integrity while keeping up appearances — that's the magic of CSS. Note, however, this doesn't affect the underlying string data.

Using ES6 for modern chunks

ES6 keeps functions concise. Here's the capitalize function using an arrow function:

const modernCapitalize = (str) => `${str[0]?.toUpperCase()}${str.slice(1)}`;

Code modernization done right, but browser compatibility is a trade-off here.

Nitty-gritties

Ever thought about the corner cases? Well, let's dive into it.

Null or undefined

A logical AND operator can shield against null or undefined:

const capitalize = (str) => str && str.charAt(0).toUpperCase() + str.slice(1);

Null who? Undefined where?

Internationalization

Strings with international characters may need .toLocaleUpperCase() for locale-specific conversion:

const localizeCapitalize = (str) => str && str.charAt(0).toLocaleUpperCase() + str.slice(1);

Voilà! Welcome to the international club. Respecting boundaries and rules!