JavaScript
How to uppercase the first letter of a string in JavaScript
In this tutorial we will see just how easy it is to capitalize the first letter first of a string in JavaScript.
To achieve this we will use two built in string methods, .toUpperCase() and the .slice() method.
const myString = 'hello, World!';
const first = myString[0]; // This gets 'h', you could also use .charAt(0)
const uppercase = first.toUpperCase();
const output = uppercase + myString.slice(1); // Get everything from index 1 onwards
console.log(output) // This logs out 'Hello, World!'
The above code is pretty simple, we access the first character of our string using square bracket notation and then save it to a variable called first. We then use the .toUpperCase method to uppercase this character, and then finally we combine it with our sliced string. We use 1 as an argument in our slice method so we can get all the characters from the index 1.
We can write this code more efficiently like this...
const myString = 'hello, World!';
const uppercase = myString[0].toUpperCase() + myString.slice(1);
[index] vs .charAt(index)
One question you might have is, should you use the .charAt() method or the square bracket notation?
Well, both are valid ways, however, square bracket notation is newer and was introduced in ES5.