How to capitalize the first letter of a string in JavaScript

To capitalize the first letter of a string in JavaScript:

  1. Use the charAt() function to isolate and uppercase 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.
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 to capitalize a string:

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:

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:

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:

.capitalize {
    text-transform: capitalize;
}

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

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

Read Next: Capitalize the first letter of each word in a string using JavaScript

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.