How to Capitalize the First Letter of Each Word in JavaScript

Have many ways to capitalize the first letter of each word. There are 2 ways below:

Using Array split() and join()

function capitalizeEachWord(sentence) { const words = sentence.split(" "); for (let i = 0; i < words.length; i++) { words[i] = words[i][0].toUpperCase() + words[i].substr(1); } var joined = words.join(" "); return joined; }
Code language: JavaScript (javascript)

Using Regex

const sentence = "how to capitalize the first letter"; sentence.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase());
Code language: JavaScript (javascript)

Leave a Reply