Converting First Charcter of String to Upper Case
本问题已经有最佳答案,请猛点这里访问。
我有一个javascript数组,它存储字符串变量。我尝试了下面的代码来帮助我将javascript变量转换为大写字母,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <html> <body> <p id="demo"> </p> <button onclick="toUppar()">Click Here</button> 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; } </body> </html> |
但我只想将javascript变量的第一个字符转换为大写。
期望输出:
如果你需要大写字母来表示你的视图,你可以简单地用CSS来表示!
1 2 3 | div.capitalize:first-letter { text-transform: capitalize; } |
以下是完整的小提琴示例:http://jsfiddle.net/wv33p/1/
使用此扩展名(根据前面的SO应答):
1 2 3 4 5 | String.prototype.first2Upper = String.prototype.first2Upper || function(){ return this.charAt(0).toUpperCase()+this.slice(1); } //usage 'somestring'.first2Upper(); //=> Somestring |
对于使用
1 2 3 | var numArray = ["one","two","three","four"] .map(function(elem){return elem.first2Upper();}); // numArray now: ["One","Two","Three","Four"] |
关于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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]"] // |
你快到了。不是将整个字符串大写,而是只将第一个字符大写。
1 2 3 4 5 6 7 8 9 10 11 | 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()) |
产量
1 | [ 'One', 'Two', 'Three', 'Four' ] |