-
split()とmap()を使用する方法:
function capitalizeFirstLetter(str) { return str.split(' ').map(function(word) { return word.charAt(0).toUpperCase() + word.slice(1); }).join(' '); } var sentence = "uppercase first letter of each word"; var capitalizedSentence = capitalizeFirstLetter(sentence); console.log(capitalizedSentence); // 出力結果: "Uppercase First Letter Of Each Word"
-
正規表現とreplace()を使用する方法:
function capitalizeFirstLetter(str) { return str.replace(/\b\w/g, function(l) { return l.toUpperCase(); }); } var sentence = "uppercase first letter of each word"; var capitalizedSentence = capitalizeFirstLetter(sentence); console.log(capitalizedSentence); // 出力結果: "Uppercase First Letter Of Each Word"
-
関数を使用する方法:
function capitalizeFirstLetter(str) { var words = str.split(' '); for (var i = 0; i < words.length; i++) { words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); } return words.join(' '); } var sentence = "uppercase first letter of each word"; var capitalizedSentence = capitalizeFirstLetter(sentence); console.log(capitalizedSentence); // 出力結果: "Uppercase First Letter Of Each Word"