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

时间:2016-02-17 06:27:48

标签: javascript uppercase

 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>

我试过这种方式,但它不起作用。我的代码中的错误是什么。真的很感激。

6 个答案:

答案 0 :(得分:3)

你忘了在分裂之前得到这个值。与var word = input.value.split("")

中一样

&#13;
&#13;
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(" ");
}
&#13;
<input type="text" id="test" maxlength="20" onkeyup="myFunction()">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用regExp

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);

这是使用regExp为字符串创建Camel Case的最佳方法。

另一种方法是使用以下功能。

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

您可以像

一样调用此函数
input=input.toUpperCaseFirstChar

答案 2 :(得分:0)

您没有将.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(" ");
        }       

答案 3 :(得分:0)

而不是使用“java脚本”使用CSS来设置表单样式 标签中为style="text-transform: capitalize;" 喜欢 <input type="text" id ="test" maxlength="20" style="text-transform: capitalize;">

答案 4 :(得分:0)

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

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()">

答案 5 :(得分:-1)

您可以使用CSS代替,这更容易:

p.capitalize { text-transform: capitalize; }
相关问题