编辑数组元素并大写字母

时间:2016-01-28 13:48:45

标签: javascript jquery

我有阵列

var myarr = [ "color - black", "color - blue", "color - Red" ]

我想替换" - "用":"并将第一个字母大写

var myarr = [ "Color: black", "Color: blue", "Color: Red" ]

我试试这个,但我不知道如何把第一个字母大写

for(var i=0; i < myarr.length; i++) {
            myarr[i] = myarr[i].replace(/ - /g, ":");
        }

5 个答案:

答案 0 :(得分:1)

for(var i=0; i < myarr.length; i++) {
        myarr[i] = myarr[i].charAt(0).toUpperCase() + myarr[i].replace(/ - /g, ":").substring(1);
    }

答案 1 :(得分:0)

这应该可以解决问题

for(var i=0; i < myarr.length; i++) {
    myarr[i] = myarr[i].replace(/ - /g, ":");
    myarr[i] = myarr[i].charAt(0).toUpperCase() + myarr[i].slice(1);
}

答案 2 :(得分:0)

试试这个:

&#13;
&#13;
var myarr = [ "color - black", "color - blue", "color - Red" ]

for(var i=0; i < myarr.length; i++) {
  myarr[i] = myarr[i][0].toUpperCase() + myarr[i].replace(/ -/g, ":").substring(1);
}

console.log(myarr);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用地图创建新阵列。我已经将“颜色”这个词大写了。和实际的颜色:

var myarr = ["color - black", "color - blue", "color - Red"];

var newArray = myarr.map(function(element) {
  var tmp = element.split("color - ")[1];
  return "Color: " + tmp.charAt(0).toUpperCase() + tmp.slice(1);
});

答案 4 :(得分:0)

以这种方式使用Array.map()方法:

&#13;
&#13;
var myarr = ["color - black", "color - blue", "color - Red"];

var nArr = myarr.map(function(str) {
  var s = str.replace(/-/g, ":");
  var a = s.slice(0, 1).toUpperCase() + s.slice(1, s.length);
  return a;
});
document.querySelector('pre').innerHTML = JSON.stringify(nArr);
&#13;
<pre></pre>
&#13;
&#13;
&#13;