JavaScriptで単語の先頭文字を大文字にする方法


  1. 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"
  2. 正規表現と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"
  3. 関数を使用する方法:

    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"