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.
For instance, we write
const s = text.replace(/(^\w|\s\w)/g, (m) => m.toUpperCase());
to call text.replace
with a regex to get the first letter of each word with regex /(^\w|\s\w)/g
.
Then we use the callback to return the matches converted to upper case with toUpperCase
to do the replacement.
^\w
matches the first letter of the first word and \s\w
matches the first letter of other words.
Conclusion
To capitalize the first letter of each word in a string using JavaScript, we can use the string replace
method.