2013-08-31 36 views
3

我有存储字符串变量在它的JavaScript数组。 我曾尝试下面的代码,帮助我的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

+0

'@ thgaskell'我需要与JavaScript数组不直接对Java脚本变量。 – Vijay

+0

在这种情况下看一看['Array.map'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map):) – thgaskell

回答

1

你几乎没有。而不是大写整个字符串,只大写第一个字符。

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

使用这个扩展(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方法

4

如果您需要呈现给你的意见上的情况下,你可以简单地使用了这样做的CSS!

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

下面是完整的小提琴例子:http://jsfiddle.net/wV33P/1/

1
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]"] 
// 
相关问题