# How to capitalize the first letter of a string in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published May 5, 2019, updated Sep 30, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/string-capitalize-javascript

> A quick article to learn how to capitalize the first letter of a string using charAt() and slice() functions in JavaScript.

To capitalize the first letter of a string in JavaScript:

1. Use the `charAt()` function to isolate and [uppercase](https://attacomsian.com/blog/javascript-string-uppercase-lowercase) the first character from the left of the string.
2. Use the `slice()` method to slice the string leaving the first character.
3. Concatenate the output of both functions to form a capitalized string. 

```javascript
const phrase = 'example'

const output = phrase.charAt(0).toUpperCase() + phrase.slice(1)

console.log(output)
// Example
```

Alternatively, you can use the use `replace()` method with [regular expressions](https://attacomsian.com/blog/javascript-regular-expressions) to capitalize a string:

```javascript
const phrase = 'example'

const output = phrase.replace(/^\w/, c => c.toUpperCase())

console.log(output)
// Example
```

You can even take one step further and create a function to transform the first character of the string to uppercase: 

```javascript
const capitalize = str => {
  if (typeof str === 'string') {
    return str.replace(/^\w/, c => c.toUpperCase())
  } else {
    return ''
  }
}
```

The above `capitalize()` function also checks the type of the passed parameter. If it is not a string, it returns an empty string.

Now just call the function whenever you want to capitalize a string:

```javascript
capitalize('google')        // Google
capitalize('how it works')  // How it works
capitalize('a')             // A
capitalize([])              // ''
capitalize()                // ''
```

If you want to capitalize all words of a paragraph on a web page, use CSS `text-transform` property instead: 

```css
.capitalize {
    text-transform: capitalize;
}
```

Now just add the `capitalize` class to your HTML paragraph element as shown below:

```markup
<p class="capitalize">Welcome to JavaScript tutorials!</p>
```

**Read Next:** [Capitalize the first letter of each word in a string using JavaScript](https://attacomsian.com/blog/javascript-capitalize-first-letter-of-each-word-in-string)
