JavaScript

How to Capitalize the First Letter of a Word Using JavaScript

There are several ways to format a string but most common ones involve the handling of capitalization. The follow two cases format a string using the infamous string methods: “replace()”, “toLowerCase()”, and “toUpperCase()”.

Case 1: Capitalize only the first character of a string

let str = "this Is A StrinG!";
let newstr = str.replace(  /^[a-z]{1}/igm,function(m){
           return m.toUpperCase()
         });
console.log(newstr);  //Output:  This Is A StrinG!

This one is pretty obvious.

Case 2: Capitalize only the first character and force the rest of string to be in lowercase

let str = "this Is A StrinG!";
let newstr = str.toLowerCase().replace(/^[a-z]{1}/igm,function(m){
           return m.toUpperCase()
         });
console.log(newstr);  //Output:  This is a string!

Try it here:

Verified by MonsterInsights