How to Capitalize First Letter of String in JavaScript 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:

  1. Get the first letter of the string using charAt() method
    const string = "string";
    
    string.charAt(0);  // Returns "s"
    
  2. Convert the first letter to uppercase using toUpperCase() method
    const string = "string";
    
    string.charAt(0).toUpperCase();  // Returns "S"
    
  3. Get the rest of the string except first letter using slice() method
    const string = "string";
    
    string.slice(1);  // Returns "tring"
    
    Note that slice(1) means get a substring from index 1 to end of the string. Alternatively, You can also use substring(1).
  4. 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"