This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(100个答案)
7年前关闭。
我有在其中存储String变量的JavaScript数组。
我尝试了以下代码,这些代码可帮助我将Javascript变量转换为大写字母,
但我只想将Javascript变量的第一个字符转换为大写。
所需的输出:
输出
(100个答案)
7年前关闭。
我有在其中存储String变量的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
最佳答案
你快到了。而不是大写整个字符串,只将第一个字符大写。
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' ]