Capitalize the first letter of a string in JavaScript
By: Ajdin Imsirovic 18 January 2021
The trick is to separate the string into the first letter and the rest of the string using charAt()
and slice()
, then run the toUpperCase()
method on the first substring, and concatenate the rest of the original string back to the uppercased first letter.
For this task, we’ll use the charAt()
method on the String prototype. For example:
1
2
3
4
5
'abcde'.charAt(0); // returns: a
'abcde'.charAt(1); // returns: b
'abcde'.charAt(2); // returns: c
'abcde'.charAt(3); // returns: d
'abcde'.charAt(4); // returns: e
Now that we have a way to get any letter, we can store it in a variable:
1
2
3
let str = 'lorem ipsum';
let firstLetter = str.charAt(0);
console.log(firstLetter); // 'l'
Now we can easily convert the firstLetter
to uppercase:
1
2
3
let str = 'lorem ipsum';
let firstLetter = str.charAt(0).toUpperCase();
console.log(firstLetter); // 'L'
From here, we need to pick one of these two approaches:
- We can concatenate the rest of the source string onto the uppercased firstLetter
- We can replace the first letter in the original string with the uppercased firstLetter
Let’s go through each solution.
Here’s first solution:
1
2
3
4
5
6
7
function uppercaseFirstChar(str) {
const firstLetter = str.charAt(0).toUpperCase();
const restOfString = str.slice(1);
return firstLetter + restOfString;
}
uppercaseFirstChar('lorem ipsum'); // 'Lorem ipsum'
Additionally, we can simplify this first solution so that it’s a simple one-liner:
Here’s the second solution, using the built-in replace()
method on the String prototype:
1
2
3
4
5
function uppercaseFirstCharV2(str) {
let updatedStr = str.replace(/^\w/, (char) => char.toUpperCase());
return updatedStr;
}
uppercaseFirstCharV2('lorem ipsum');
The ^\w
regex selects the first letter of the first word. A great website for understanding regex and testing it out is https://regexr.com.
Note:
This exercise comes from Book 3
of my book series on JS, available on Leanpub.com.