How to capitalize first letter in JavaScript

In this post we go over seven examples on how to capitalize the first letter in JavaScript.

Dec 1, 2022 | Read time 6 minutes

🔔 Table of contents

This post will go over a few options to capitalize the first letter in JavaScript.

The easiest and most straightforward way is to use JavaScript’s in-built toUpperCase and toLowerCase methods. These methods convert the case of an entire string, so you can use them on a sentence to capitalize the first letter.

Option 1: Using toUpperCase() and slice() method

// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1);
}

capitalizeFirstLetter("i like eating apples") // This will return "I like eating apples" 

This is the most basic option and supported across browsers. Performance is good too, if we run it against JS Perf - it can complete 10,889,187 operations per second.

A variant of the above code is to use the charAt function instead of accessing the string array via index.

// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

capitalizeFirstLetter("i like eating apples") // This will return "I like eating apples" 

Performance is similar to the previous example, it can complete 10,875,535 operations per second.

Option 2: Using the replace() method with regular expressions

Another way to do this is through regular expressions. You can use a regular expression to match the first letter of the sentence and use the JavaScript replace method to substitute the lowercase letter with an uppercase one.

// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
    return string.replace(/^./, string[0].toUpperCase());
}

capitalizeFirstLetter("i like eating apples") // This will return "I like eating apples" 

This option is slower than option 1, with 4,632,536 operations per second. Additionally there are limitions on browsers. Based on the https://kangax.github.io/compat-table/es2016plus/ we can see it is not supported in IE11 and Safari versions 15/16.

Option 3: Using the String.prototype method

String.prototype is an object containing properties and methods that can be used to extend the functionality of Strings in JavaScript. We can extend the string using prototypes as follows:

// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

// we can use it as follows
"i like eating apples".capitalizeFirstLetter();

This is the slowest performing with 1,977,828 operations per second.

Option 4: Using ES6 destructuring feature

Destructuring is a feature of ECMAScript (ES6) which allows users to extract values from arrays, or properties from objects, and store them in distinct variables. It is used to simplify access to array or object values.

const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();

Option 5: Using the substring() method

If you want to quickly capitalize the first letter of a sentence without having to worry about the rest of the string, you can use the JavaScript substring method. This allows you to extract the first letter of the string (0 to 1 index) so you can capitalize it. We then concat that with the remaining of the sentence.

function capitalizeFirstLetter(str){
    return str.substring(0,1).toUpperCase() + str.substring(1);
}

Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring the substring method takes up to two parameters. The first parameter is the start index, and the second is the end index.

A few notes when using the substring method:

  • string.substring(1) is faster than string.slice(1).

Option 6: Fully support unicode and internationalization

The previous solutions addresses the basic case of english/ latin characters. However it does not cater for Asian characters, emoji’s, and other high Unicode-point-value characters in many browsers.

The below will cater for this. We will first check for UTF-32 and then fallback to UTF-16 using the toLocaleUpperCase method.

const capitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toLocaleUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toLocaleUpperCase() + S.substring(2) :
            S.charAt(0).toLocaleUpperCase() + S.substring(1)
        );
    };

Option 7: CSS only to capitalize the first letter

The the majority of cases, using CSS would be adequate. To use CSS to capitalize the first letter of a sentence, you can use the text-transform property, like this:

<p>This sentence has the first letter capitalized.</p>

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

A thing to keep in mind is that ::first-letter pseudo element works ONLY on elements with a display value of block, inline-block, table-cell, list-item or table-caption. It will not work if its any other display value - eg flex.

Tip: Prefer CSS over JavaScript

Using the CSS first-letter pseudo element would be the prefered option in most cases. However if this does not work when you are working with elements with display values outside of block, inline-block, table-cell, list-item or table-caption. For example, this would not work with input values, etc. In this case we need to fallback with JavaScript.

Summary

These methods are useful when it comes to capitalizing the first letter of a sentence in JavaScript. Whether you prefer regular expressions, the substring() method, ES6 desctructuring one liners, catering for internationalization/ unicode and CSS only with first-letter, you can use any of these methods to make your text look neat and organized.

We prefer to use CSS in most cases, but if its absolutely necessary, we can fallback the the various JavaScript options.

👋 About the Author

G'day! I am Huy a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

Follow along on Twitter , GitHub and YouTube