How to Capitalize the First Letter in a String in JavaScript

I’m still kind of spoiled by the baked in functions in PHP (as well as Ruby and Python for this particular task). For instance, something like capitalizing the first letter of a string is a trivial task in most languages:

<?php
// Capitalize first letter with PHP
ucfirst('some string that needs the first character capitalized');
PHP
# Capitalize first letter with Python
"some lower case string".capitalize()
JavaScript
# Capitalize first letter with Ruby
"some lower case string".capitalize
Ruby

JavaScript on the other hand, assuming you’re not using php.js, the act
of capitalizing the first letter of a string is a bit more involved.

At the most basic level, the steps involved to capitalize the first character of
a string are:

  1. Firstly, isolate the first character from the rest of the string.
  2. Then, capitalize the character.
  3. Finally, concatenate the now capitalized letter with the rest of the string.

Consequently, that doesn’t even take into consideration if you want to force the rest of the string to be lower cased or not!

More than one way to skin a cat

As outlined, you can capitalize the first character of a string
quite a few different ways, some include regular expressions and some not.

const lower = 'this is an entirely lowercase string';
const upper = lower.charAt(0).toUpperCase() + lower.substring(1);
JavaScript

Alternatively, to save a few key strokes, you can use slice() instead of substring to achieve the same results:

const lower = 'this is an entirely lowercase string';
const upper = lower.charAt(0).toUpperCase() + lower.slice(1);
JavaScript

Of course, if you are comfortable with regular expressions, you can use the
replace() method and do things this way:

const lower = 'this is an entirely lowercase string';
const upper = lower.replace(/^\w/, function (chr) {
  return chr.toUpperCase();
});
JavaScript

Furthermore, you can even take it one step by using more modern (and shorter) syntax like ES6 arrow functions and shorthand return:

const lower = 'this is an entirely lowercase string';
const upper = lower.replace(/^\w/, chr => chr.toUpperCase());
JavaScript

A bit more code than PHP but it gets the job done! It works in [modern] web
browsers as well as Node.js!

To clarify, these examples all assume your string is already lowercased. If it’s not and you’re concerned with making sure only the first letter is capitalized, simply apply .toLowerCase() to your string before processing it.

Making the code a reusable function

Wrapping up the previous code into a function is extremely easy as well, and we can build in support to force the string to be lowercased or not:

const upperCaseFirst = (str, forceLower = false) => {
  if (typeof str === 'string') {
    if (forceLower) {
      str = str.toLowerCase();
    }

    return str.replace(/^\w/, chr => chr.toUpperCase());
  }

  // You could error here, or return the original variable, your call:
  return '';
};
JavaScript

Of course, if you’re into TypeScript, you can properly type the function and
omit the sanity checks if you can guarantee the types at runtime:

const upperCaseFirst = (str: string, forceLower?: boolean): string => {
  if (forceLower) {
    str = str.toLowerCase();
  }

  return str.replace(/^\w/, chr => chr.toUpperCase());
};
JavaScript

If you happen to have an array of strings that need to be capitalized, you can feed our upperCaseFirst function in via Array.map():

const lowers = ['first', 'second', 'third'];
const uppers = lowers.map(upperCaseFirst);
JavaScript

If you want to force the strings to be lowercased:

const mixed = ['FiRsT', 'sEcOnD', 'tHiRd'];
const uppers = lowers.map((lower) => upperCaseFirst(lower, true));
JavaScript

Also, if you’re okay with adding a new code to your project, you can check out my string lib called “Luthier” which has an upperCaseFirst() method and many other string utilities. Check it out on GitHub

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.