How do I make the first letter of a string uppercase in JavaScript?
Here's your quick fix to make the first letter of a string uppercase in JavaScript:
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:
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:
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:
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:
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:
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:
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:
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
:
Null who? Undefined where?
Internationalization
Strings with international characters may need .toLocaleUpperCase()
for locale-specific conversion:
Voilà! Welcome to the international club. Respecting boundaries and rules!
Was this article helpful?