2013-08-31 38 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]"] 
// 
相關問題