menu

How to Uppercase the First Letter of a String Using JavaScript

In this short tip post, we will learn how to capitalize (change it to Uppercase) the first letter of a string using JavaScript.

Objective

To change the first letter of a string to uppercase using JavaScript.

Approach

We can use charAt and slice() function to change the first letter case to uppercase.

We can use charAt to extract first letter of a given string and change it to uppercase. We can the use slice() method to extract the remaining string and then combine both to yeild the result.

Code

function changeCaseFirstLetter(params) {
        if(typeof params === 'string') {
                return params.charAt(0).toUpperCase() + params.slice(1);
        }
        return null;
}

console.log(changeCaseFirstLetter('shahid')) // Shahid
console.log(changeCaseFirstLetter(0)); // null

Check out the codepen for a live demo.

See the Pen
change first letter case
by Shahid Shaikh (@codeforgeek)
on CodePen.

Love JavaScript? Learn more about it here.