JavaScript Capitalize First Letter of a String

Dec 22, 2022 · Snippet · 1 min, 172 words

Make the first letter of a string uppercase in JavaScript.

Basic Solution

The basic solution is:

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase()   string.slice(1);

console.log(capitalizeFirstLetter('foo')); // Foo

Object-oriented Approach

Here's a more object-oriented approach:

Object.defineProperty(String.prototype, 'capitalize', {
  value: function() {
    return this.charAt(0).toUpperCase()   this.slice(1);
  enumerable: false

You'd call the function, like this:

"hello, world!".capitalize();

With the expected output being:

"Hello, world!"

Using CSS

p::first-letter {


No comments yet…