Javascript - 如何将每个单词的首字母大写

Javascript - How to capitalize first letter of each word

 test <input type="text" id ="test" maxlength="20" onkeyup="myFunction()">
    <script>
        function myFunction(){
            var input = document.getElementById("test");
            var word = input.split(" ");
            for(var i = 0; i< word.length; i++){
                word[i] = word[i].charAt(0).toUpperCase()+word[i].slice(1).toLowerCase();
            }
            return word.join(" ");
        }            
    </script>

这个方法我试过了,还是不行。我的代码中有什么错误。真的很感激。

拆分前忘记获取值了。如 var word = input.value.split("")

function myFunction() {
  var input = document.getElementById("test");
  var word = input.value.split(" ");
  for (var i = 0; i < word.length; i++) {
    word[i] = word[i].charAt(0).toUpperCase() + word[i].slice(1).toLowerCase();
  }
  input.value = word.join(" ");
}
<input type="text" id="test" maxlength="20" onkeyup="myFunction()">

您可以使用正则表达式

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
    return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
  }).replace(/\s+/g, '');
}

camelize(input);

这是使用正则表达式为字符串制作驼峰式大小写的最佳方式。

另一种方法是使用以下函数。

String.prototype.toUpperCaseFirstChar = function() {
    return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}

你可以像这样调用这个函数

input=input.toUpperCaseFirstChar

您可以改用CSS,这样更容易:

p.capitalize { text-transform: capitalize; }

您没有将 .value 与元素对象一起使用。

你需要任何字符串来拆分它。

https://jsfiddle.net/9hyw2vLb/3/

test <input type="text" id ="test" maxlength="20" onkeyup="return myFunction();">

        myFunction= function(){
            var input = document.getElementById("test").value;
            var word = input.split(" ");
            for(var i = 0; i< word.length; i++){
                word[i] = word[i].charAt(0).toUpperCase()+word[i].slice(1).toLowerCase();
            }
            console.log(word.join(" "));
            return word.join(" ");
        }       

而不是使用 "java script" 使用 CSS 来设置表单样式 style="text-transform: capitalize;" 在标签中 像 <input type="text" id ="test" maxlength="20" style="text-transform: capitalize;">

其他人已经回答正确,但这里有一个使用方法链的版本。我发现它更具可读性。

function myFunction() {
  var input = document.getElementById('test');

  var capitalizedWords =
    input
      .value
      .split(' ')
      .map(function(word) {
        return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
      })
      .join(' ');
  
  input.value = capitalizedWords;
}
<input type="text" id="test" maxlength="20" onkeyup="myFunction()">