w3docs logo
  1. Snippets
  2. JavaScript
  3. How to Capitalize the First Letter in a String in JavaScript

How to Capitalize the First Letter in a String in JavaScript

To capitalize the first letter in a string is easy if you undertake some steps.

First of all you should get the first letter of the string by setting the charAt() method at 0 index:

w3docs logo Javascript charAt method
let string = "w3docs.com"; console.log(string.charAt(0)); // Returns "w"

Next, you should make the first letter uppercase with the toUpperCase() method:

w3docs logo Javascript the first letter uppercase
let string = "w3docs.com"; console.log(string.charAt(0).toUpperCase()); // Returns "W"

Then, you should get the remainder of the string with the help of the slice() method.

w3docs logo Javascript get the remainder of the string slice method
let string = "w3docs.com"; console.log(string.slice(1)); // Returns "3docs.com"
Use slice(1) to start from the second character to the end of the string.

The final step you should take is creating a function accepting a string as only argument and returns the concatenation of the first capitalized letter and the remainder of the string:

w3docs logo Javascript returns the concatenation of the first capitalized letter
let string = "w3docs.com"; function capitalizeFirstLetter(str) { console.log(str.charAt(0).toUpperCase() + str.slice(1)); } capitalizeFirstLetter(string); // Returns "W3docs.com"

You may also add that function to the String.prototype to use it directly on a string:

w3docs logo Javascript add that function to the String.prototype
var string = "w3docs.com"; Object.defineProperty(String.prototype, 'capitalizeFirstLetter', { value: function () { console.log(this.charAt(0).toUpperCase() + this.slice(1)); }, writable: true, // so that one can overwrite it later configurable: true // so that it can be deleted later }); string.capitalizeFirstLetter(); // Returns "W3docs.com"

JavaScript Strings

JavaScript strings are used to store and manipulate text. No separate type exists for a single character. The strings internal format is UTF-16. A string represents either zero or more characters that are written inside quotes.

The toUpperCase() method returns the string value that is converted to uppercase. It does not affect any special character, digits, and alphabets already in uppercase.

Do you find this helpful?