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"