Sometimes, we want to change the first letter of variable to upper case with JavaScript.
In this article, we’ll look at how to change the first letter of variable to upper case with JavaScript.
How to change the first letter of variable to upper case with JavaScript?
To change the first letter of variable to upper case with JavaScript, we can use the string replace
method.
For instance, we write
const str = "hello world";
const newStr = str.toLowerCase().replace(/\b[a-z]/g, (letter) => {
return letter.toUpperCase();
});
to call str.toLowerCase
to convert all the letters in str
to lower case.
Then we call replace
with a regex that gets the first letter of each word.
\b
means word boundary, so we get the first lower case letter of each word.
We use the g
flag to get all matches.
Then we replace them all with upper case letter by using a function that returns letter.toUpperCase
where letter
is the match being replaced.
Conclusion
To change the first letter of variable to upper case with JavaScript, we can use the string replace
method.