0

I have array

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

I want to replace " - " with ":" and capitalize the first letter

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

I try this but I don't know how to capitalize the first letter

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

5 Answers5

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

This should do the trick

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);
}
Sabaz
  • 4,794
  • 2
  • 18
  • 26
0

Try this:

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);
Paulo Menezes
  • 539
  • 3
  • 15
0

You can use a map to create a new array. I've capitalised both the word 'color' and the actual color:

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);
});
NMunro
  • 890
  • 5
  • 20
0

use Array.map() method this way:

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);
<pre></pre>
Jai
  • 74,255
  • 12
  • 74
  • 103