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'
.