<Aaron />

How to Capitalize the First Letter in a String

Jan 09, 2020 3 min read

This is a quick primer on how to capitalize the first letter of a string using JavaScript. Outside of longer form content (think complete sentences), I prefer to standardize all my strings to be lowercase. This helps ensure a consistent formatting whenever I am working with any string values. Then whenever I need to capitalize the first letter of a string I will do so programmatically on a case-by-case basis.

Frontend Solution

On the frontend my preferred solution is to use the CSS property 'text-transform: capitalize'. Typically, I will make a helper class with only this property and then wrap my target word in a span containing my helper class like so.

1.capitalize {
2 text-transform: capitalize;
3}
1<p>
2 My name is <span class="capitalize">aaron</span> and I live in
3 <span class="capitalize">seattle</span>.
4</p>
5
6// => My name is Aaron and I live in Seattle.

If you ae using a CSS-in-JS or any other modular CSS strategy then I would advise creating a small shared CSS file for this type of helper.

Backend / JavaScript Way

If I am working on the backend or anywhere the solution above wouldn't apply then it's time to break out some JavaScript. The general logic behind my solutions is to isolate the first character, capitalize it, then join (concatenate) it with the rest of the string. I will outline several methods to do this below

Using String methods.

1const string = "my favorite food is pizza"
2
3function capitalize(str) {
4 const upper = str.charAt(0).toUpperCase() // "M"
5 const restOfTheString = str.substring(1) // "y favorite food is pizza"
6 const formattedString = upper.concat("", restOfTheString) // "My favorite food is pizza"
7
8 // return our formatted string
9 return formattedString
10}

Using an Array

1const string = "i love to scuba dive"
2
3function capitalize(str) {
4 const strArray = str.split("") // ["i", " ", "l", "o"...]
5 strArray[0] = strArray[0].toUpperCase() // ["I", " ", "l", "o"...]
6 const formattedString = strArray.join("") // "I love to scuba dive"
7
8 // return our formatted string
9 return formattedString
10}

We can also use Regex

1const string = "coffee is wonderful"
2
3function capitalize(str) {
4 return str.replace(/^\w/, char => char.toUpperCase()) // "Coffee is wonderful"
5}

I hope this was helpful! As always, these are just a few of the myriad ways to capitalize the first letter of a string.

Cheers!

Find a mistake? Help me fix it by submitting a pull request.

← back to all posts