How to Uppercase the First Letter of a String with JavaScript

Last updated on: by Digamber
JavaScript capitalize the first letter of the string will be explored in this tutorial. In order to capitalize the first letter of a string in JavaScript, you have plenty of options available in JavaScript. We are going to learn different methods here. Moreover, we will tell you which one is ideal for you when it comes to plain JavaScript.

JavaScript capitalize first letter

When it comes to common string operations, turning the first letter uppercase is a common thing.

To achieve the same, you need to use two functions. The first function will uppercase the very first letter. The second function will return the string starting from the second character.

const name = 'avengers'
const userName = name.charAt(0).toUpperCase() + name.slice(0)
console.log(userName)
// Output: Aavengers

The function will also check if the parameter you have passed is a string or not. It will return an empty string otherwise. Capitalizing string in JavaScript can be achieved easily with these examples.

let CapitalizeString = (string) => {
   if(typeof string !== 'string') {
     return 'This is not string!'
   }
}
 
CapitalizeString('avengers') 
//Output: 'Avengers'
CapitalizeString('c')      
//Output: 'C'
CapitalizeString(11)       
//Output: 'This is not string!'

Well, you don’t have to use the string.charAt (0). For instance, you may use string [0], but older versions of IE do not support it.

Well, you will come across solutions online that suggest you add the function to the String prototype:

let myString = 'hello world';
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
myString.capitalize()
// Output: Hello world

To make use of ‘this’, we use a regular function. ‘Arrow functions’ will not work in this case. ‘This’ in arrow functions does not point to the current object

We wouldn’t call it the ideal solution given the fact that editing a prototype is not recommended at all. Moreover, this solution is slower compared to an independent function.

If it is mainly meant for a presentation purpose, then we recommend using CSS. All that you have to do is to add a ‘capitalize’ class to the HTML paragraph.

.capitalize {
  text-transform: capitalize;
}
p:first-letter {
    text-transform:capitalize;
}

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.