Sometimes, we want to change the first letter of each word to upper case with JavaScript.
In this article, we’ll look at how to change the first letter of each word to upper case with JavaScript.
Change the First Letter of Each Word to Upper Case with JavaScript
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' .
Conclusion
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.