Capitalize the First Letter of a String in JavaScript

Jun 15, 2020

Capitalizing the first letter of a JavaScript string is easy if you combine the string toUpperCase() method with the string slice() method.

const str = 'captain Picard';

const caps = str.charAt(0).toUpperCase() + str.slice(1);
caps; // 'Captain Picard'

The first part converts the first letter to upper case, and then appends the rest of the string.

If you want to capitalize the first letter of every word in a string, you can use split() to split the string into words and then join() the string back together as shown below.

const str = 'captain picard';

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

const caps = str.split(' ').map(capitalize).join(' ');
caps; // 'Captain Picard'

Using CSS

Keep in mind that you don't need JavaScript to capitalize a string on the frontend. CSS can do that for you:

.capitalize {
  text-transform: capitalize;
}

For example, the below <div> has the capitalize class, with 'captain picard' as its inner text. CSS can convert all words in a string to uppercase.

captain picard

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

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!