Sometimes, we want to capitalize the first letter of each word in a string using JavaScript.
In this article, we’ll look at how to capitalize the first letter of each word in a string using JavaScript.
How to capitalize the first letter of each word in a string using JavaScript?
To capitalize the first letter of each word in a string using JavaScript, we can use the string replace method with a regex.
For instance, we write
const s = text.replace(/(^\w|\s\w)/g, (m) => m.toUpperCase());
to call replace on the string text with a regex to match the start of each word in the string with (^\w|\s\w).
We use the g flag to get all matches.
Then we call it with a callback to return the matches converted to upper case with toUpperCase.
Conclusion
To capitalize the first letter of each word in a string using JavaScript, we can use the string replace method with a regex.
