Robin van der Vleuten

How to capitalize strings in JavaScript

To capitalize a JavaScript string, you do not need another npm dependency. Plain JavaScript is enough, and CSS may be the better choice if the change is only visual.

TLDR;

js
const chars = 'hello'
chars[0].toUpperCase() + chars.slice(1) // 'Hello'

Walk through all steps

Start with the basic idea: a string is a sequence of characters. You can think of this:

js
const chars = ['h', 'e', 'l', 'l', 'o'].join('') // 'hello'

Uppercase the first letter

You can access an array item by index. If we need the letter e, we use index 1, because arrays start at 0.

Since ECMAScript 5, strings can be treated as array-like objects, so the same bracket access works on a string:

js
// We get the first letter by accessing the character at index zero.
const chars = ['h', 'e', 'l', 'l', 'o']
chars[0] // 'h'
// We get the first letter by using the `charAt()` method with index zero.
const chars = 'hello'
chars[0] // 'h'

Now that we have the first letter, call String.prototype.toUpperCase() on it. The method returns a new uppercase string instead of changing the original one. The MDN docs have more detail.

js
const chars = 'hello'
chars[0].toUpperCase() // 'H'

Slice the rest of the letters

Next, get the rest of the string after the first character. For arrays, Array.prototype.slice returns a portion between a start and end index. The MDN docs explain the method in more detail.

We do not want the first character, so the slice starts at 1. Our example word has 5 characters, and because arrays start at 0, the last index is 4.

js
const chars = ['h', 'e', 'l', 'l', 'o']
chars.slice(1, 4) // ['e', 'l', 'l', 'o']

That is not useful when you do not know the length upfront. Use the length property instead:

js
const chars = ['h', 'e', 'l', 'l', 'o']
chars.slice(1, chars.length) // ['e', 'l', 'l', 'o']

Because slicing to the end is common, you can skip the end index:

js
const chars = ['h', 'e', 'l', 'l', 'o']
chars.slice(1) // ['e', 'l', 'l', 'o']

For strings, use String.prototype.slice. It works the same way. The MDN docs cover the string version.

js
const chars = 'hello'
chars.slice(1) // 'ello'

Now combine the uppercased first character with the rest of the string:

js
const chars = 'hello'
chars.charAt(0).toUpperCase() + chars.slice(1) // 'Hello'

That gives us a capitalized string.

Just use CSS

If you only need the text to look capitalized on a web page, use CSS instead:

html
<style>
.capitalize {
text-transform: capitalize;
}
</style>
<span class="capitalize"> hello </span>