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.

Pankaj Kumar
Pankaj Kumar

Pankaj Kumar is the founder and CEO of CodeForGeek, with more than 14 years in IT. He is an open-source enthusiast who enjoys sharing what he learns through CodeForGeek and YouTube, with a focus on Python, data analytics, machine learning, Angular, Node.js, and Kafka.

Articles: 335