Capitalize the First Letter of a String in JavaScript

Jul 24, 2019

JavaScript doesn't have a built-in function to convert the first letter of a string to uppercase. However, you can capitalize the first letter of a string with one line of vanilla JS. You can also use lodash or CSS. In this tutorial, you'll learn to use all 3.

Using Vanilla JS

JavaScript has a String#uppercase() function that converts an entire string to uppercase. That means you can capitalize the first character and combine it with the substring containing everything but the first character.

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);

capitalize('dog'); // 'Dog'
capitalize('cAT'); // 'CAT'

Using Lodash

Lodash's capitalize() function also capitalizes the first character in a string. It also converts the remaining characters to lowercase.

const _ = require('lodash');

_.capitalize('dog'); // 'Dog'
_.capitalize('cAT'); // 'Cat'

Using CSS

Depending on your use case, you might not need JavaScript at all. CSS text-transform: capitalize capitalizes the first letter of each word in the string.

.capitalize {
  text-transform: capitalize;

So given the string 'capitalize using CSS', the browser will render the string as 'capitalize using CSS'.

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials