Sometimes, we want to capitalize first letter of each word in JavaScript.
In this article, we’ll look at how to capitalize first letter of each word in JavaScript.
How to capitalize first letter of each word in JavaScript?
To capitalize first letter of each word in JavaScript, we can use the string’s replace method.
For instance, we write:
const str = 'foo bar baz'
const newStr = str.toLowerCase().replace(/^\w|\s\w/g, (letter) => {
return letter.toUpperCase();
})
console.log(newStr)
We call replace with a regex to match the first letter of each word and a callback that replace those letters with an upper case letter.
Therefore, newStr is 'Foo Bar Baz'.
Conclusion
To capitalize first letter of each word in JavaScript, we can use the string’s replace method.