Categories
JavaScript Answers

How to Change the First Letter of Each Word to Upper Case with JavaScript?

Spread the love

To change the first letter of each word to upper case with JavaScript, we can use the JavaScript string’s replace method with a callback to change the first letter of each word to uppercase.

For instance, we can write:

const str = "hello world";
const newStr = str.toLowerCase().replace(/b[a-z]/g, (letter) => {
  return letter.toUpperCase();
});
console.log(newStr)

We call str.toLowerCase to convert str to lower case.

Then we call replace on it with a regex to match all lowercase letters that are the first letter of a word with /b[a-z]/g .

The callback gets the matched letter and call toUpperCase on it.

Therefore, newStr is 'Hello World' .

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 *