How to Capitalize First Letter of String in JavaScript
Page content
In this quick tutorial, we’ll learn how to capitalize the first letter of a String in JavaScript.
‘capitalize’ Function
You can use this custom made capitalize() function to capitalize the first letter of a string:
// es5 way
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// es6 way using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('');
‘capitalize’ Function Details
Let’s look at the steps involved to come up with capitalize() function:
- Get the first letter of the string using
charAt()methodconst string = "string"; string.charAt(0); // Returns "s" - Convert the first letter to uppercase using
toUpperCase()methodconst string = "string"; string.charAt(0).toUpperCase(); // Returns "S" - Get the rest of the string except first letter using
slice()methodNote thatconst string = "string"; string.slice(1); // Returns "tring"slice(1)means get a substring from index 1 to end of the string. Alternatively, You can also usesubstring(1). - Finally, add the first uppercase letter to rest of the string
var string = "string"; function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } capitalize(string); // Returns "String"
Add ‘capitalize’ to String methods
We can also add our custom made capitalize() function to String.prototype methods so that we can directly use that on a string.
var string = "string";
/* this is how methods are defined in prototype of any built-in Object */
Object.defineProperty(String.prototype, 'capitalize', {
value: function () {
return this.charAt(0).toUpperCase() + this.slice(1);
},
writable: true, // so that one can overwrite it later
configurable: true // so that it can be deleted later
});
string.capitalize(); // Returns "String"
Capitalize First Letter of each word in a given String
We can use the capitalizeSentence function to capitalize first letter of each word in a sentence:
function capitalizeSentence(sentence) {
return sentence
.split(" ")
.map(string => string.charAt(0).toUpperCase() + string.slice(1))
.join(" ");
}
capitalizeSentence("a quick brown fox jumps over the lazy dog");
// "A Quick Brown Fox Jumps Over The Lazy Dog"
Edge Case: Empty Strings
Every version above assumes there’s at least one character to grab. Feed the ES5 version an empty string and charAt(0) quietly returns "", so the whole thing degrades gracefully:
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
capitalize(""); // Returns ""
The ES6 destructuring version behaves very differently. Destructuring an empty string still runs — a string is iterable, and iterating "" simply produces zero elements — so first ends up undefined rather than an empty string, and calling .toUpperCase() on undefined throws:
const capitalize = ([first, ...rest]) => first.toUpperCase() + rest.join('');
capitalize("");
// Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
That’s a real, reproducible crash, not a theoretical one — run it in Node and you’ll get exactly that TypeError. If your input can ever be an empty string (form fields, optional API responses, a .split() result with a trailing delimiter), either guard for it explicitly or stick with the charAt() version, which handles it for free:
const capitalize = (string) => {
if (!string) return string;
const [first, ...rest] = string;
return first.toUpperCase() + rest.join('');
};
Edge Case: Unicode, Accents, and Locale
Plain accented letters aren’t a problem — toUpperCase() handles them correctly out of the box:
capitalize("école"); // Returns "École"
capitalize("índice"); // Returns "Índice"
Where things get subtle is locale-sensitive casing. The classic example is Turkish, which has two distinct versions of the letter “i”: a dotted one and a dotless one. JavaScript’s locale-agnostic toUpperCase() always maps lowercase i to I, but the Turkish-locale rule maps it to İ (dotted capital I) instead:
"i".toUpperCase(); // "I" (locale-agnostic default)
"i".toLocaleUpperCase(); // "I" (uses the runtime's default locale)
"i".toLocaleUpperCase('tr-TR'); // "İ" (explicit Turkish locale)
capitalize("istanbul"); // "Istanbul"
"istanbul".charAt(0).toLocaleUpperCase('tr-TR')
+ "istanbul".slice(1); // "İstanbul"
For most content this distinction never matters, but if you’re capitalizing user-facing text in an app that supports Turkish (or another locale with similar casing exceptions, like Azerbaijani), swap toUpperCase() for toLocaleUpperCase(locale) and pass the user’s actual locale rather than relying on the default.
Should You Even Extend String.prototype?
The Object.defineProperty trick above works, but adding methods to a built-in prototype is generally considered bad practice outside of a quick script or a coding exercise, for a few concrete reasons:
- Naming collisions with the language itself. If a future ECMAScript version ever adds a native
String.prototype.capitalize, your custom version silently shadows it (or conflicts with it, depending on load order) — and every caller in your codebase is now depending on your semantics without knowing it. - Naming collisions with libraries. Any third-party library that also happens to patch
String.prototype.capitalize— directly or via a polyfill — will silently overwrite or be overwritten by yours, and whichever one loads last wins. These bugs are miserable to track down because nothing throws; a string just starts behaving differently. - Surprise for other maintainers. A method appearing on every string in your codebase, defined nowhere near where it’s used, is a common source of confusion for anyone new to the code (including future you).
In practice, prefer a plain exported utility function (capitalize(str)) over patching the prototype. It’s just as easy to call, it’s grep-able, and it can never collide with anything outside your own module.
Do You Even Need JavaScript?
If capitalizing the first letter is purely a display concern — you’re not transforming or storing the data, just presenting it — you don’t need JavaScript at all. CSS has a built-in text-transform: capitalize that does exactly this, entirely on the styling layer:
.name {
text-transform: capitalize;
}
<span class="name">john doe</span>
<!-- renders as: John Doe -->
This capitalizes the first letter of every word (similar to the capitalizeSentence() function above), runs with zero JavaScript, respects the user’s locale automatically, and never mutates the underlying string — the DOM/JS value stays "john doe", only the rendering changes. Reach for the CSS property whenever the goal is “make this look capitalized on screen”; save the JavaScript functions above for when you actually need the capitalized string itself — to send to an API, store in a database, or compare against other data.