Categories
JavaScript Answers

How to capitalize the first letter of each word in a string using JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *