How to capitalize the first letter of a string in JavaScript

published: 09 Apr 2022

2 min read

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>Welcome to JavaScript tutorials!</p>

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

How to capitalize the first letter of a string in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming