我有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>
Run Code Online (Sandbox Code Playgroud)
但我想只将Javascript变量的第一个字符转换为大写字母.
期望的输出: One,Two,Three,Four
如果你需要大写字母来展示你的观点,你可以简单地使用css来做到这一点!
div.capitalize:first-letter {
text-transform: capitalize;
}
Run Code Online (Sandbox Code Playgroud)
这是完整的小提琴示例:http://jsfiddle.net/wV33P/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())
Run Code Online (Sandbox Code Playgroud)
输出
[ 'One', 'Two', 'Three', 'Four' ]
Run Code Online (Sandbox Code Playgroud)