将字符串的第一个字符转换为大写字母

时间:2013-08-31 09:15:31

标签: javascript html

我有一个JavaScript Array,可以在其中存储String变量。 我试过下面的代码,帮助我将Javascript变量转换为大写字母,

<html>
<body>

    <p id="demo"></p>

    <button onclick="toUppar()">Click Here</button>

    <script>
    Array.prototype.myUcase=function()
    {
        for (i=0;i<this.length;i++)
          {
          this[i]=this[i].toUpperCase();
          }
    }

    function toUppar()
    {
        var numArray = ["one", "two", "three", "four"];
        numArray.myUcase();
        var x=document.getElementById("demo");
        x.innerHTML=numArray;
    }
    </script>

</body>
</html>

但我想只将Javascript变量的第一个字符转换为大写字母。

所需的输出:One,Two,Three,Four

4 个答案:

答案 0 :(得分:5)

如果你需要大写字母来展示你的观点,你可以简单地使用css来做到这一点!

div.capitalize:first-letter {
  text-transform: capitalize;
}

这是完整的小提琴示例:http://jsfiddle.net/wV33P/1/

答案 1 :(得分:4)

使用此扩展程序(as per previous SO-answer):

String.prototype.first2Upper = String.prototype.first2Upper || function(){
 return this.charAt(0).toUpperCase()+this.slice(1);
}
//usage
'somestring'.first2Upper(); //=> Somestring

对于使用map并结合此扩展程序的数组,将是:

var numArray = ["one", "two", "three", "four"]
               .map(function(elem){return elem.first2Upper();});
// numArray now: ["One", "Two", "Three", "Four"]

See MDN有关map方法的解释和填充

答案 2 :(得分:2)

你快到了。而不是大写整个字符串,只大写第一个字符。

Array.prototype.myUcase = function()
{
    for (var i = 0, len = this.length; i < len; i += 1)
    {
          this[i] = this[i][0].toUpperCase() + this[i].slice(1);
    }
    return this;
}

var A = ["one", "two", "three", "four"]
console.log(A.myUcase())

<强>输出

[ 'One', 'Two', 'Three', 'Four' ]

答案 3 :(得分:2)

Array.prototype.ucfirst = function () {

    for (var len = this.length, i = 0; i < len; i++) {

        if (Object.prototype.toString.call(this[i]) === "[object String]") {
            this[i] = (function () {
                return this.replace(
                    /\b([a-z])[a-z]*/ig,
                    function (fullmatch, sub1) {
                        return sub1.toUpperCase() + fullmatch.slice(1).toLowerCase();
                    }
                );
            }).call(this[i]);
        }

    }
    return this;
};

console.log(["conVertInG", "fIRST", "ChaRcteR", "OF", new Array, String, new String("string tO UPPER CASE [duPLicatE]")].ucfirst());
//
// ["Converting", "First", "Charcter", "Of", [], String(), "String To Upper Case [Duplicate]"]
//
相关问题