JavaScript Capitalize First Letter of a String

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 {
    text-transform:capitalize;
}

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.