3

I have an array

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

And I want want to replace " - " with ":" and capitalize the first letter of every word in that array:

var myarr = [ "Color: Black", "Color: Blue", "Color: Red" ]

I try

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

But it works only for the first word

thanksd
  • 54,176
  • 22
  • 157
  • 150
Zarkoeleto
  • 133
  • 1
  • 2
  • 5

4 Answers4

5

You can use another regex to swap letters for their capitals in a function. Something like this will work:

String.prototype.capitalize = function() {
    return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};


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

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

console.log(myarr)

You can see it working here: https://jsfiddle.net/igor_9000/c7tqraLo/ The original SO question here: Capitalize words in string

Community
  • 1
  • 1
Adam Konieska
  • 2,805
  • 3
  • 14
  • 27
3

A map function will take care of that for you.

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

myarr = myarr.map(function(str){
  return str.charAt(0).toUpperCase() + str.slice(1).replace(/ -/, ':');
});
azywiak
  • 41
  • 4
1

You can map your array and return the changed items

var myarr   = [ "color - black", "color - blue", "color - Red" ],
    ucfirst = function(x) { return x.charAt(0).toUpperCase() + x.slice(1) };

myarr = myarr.map(function(item) {
    var parts = item.split('-').map(function(x) { return x.trim() });
    return ucfirst( parts[0] ) + ' : ' + ucfirst( parts[1] );
});

document.body.innerHTML = '<pre>' + JSON.stringify(myarr, null, 4) + '</pre>';
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

you can try something like

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

// function to capitalize the first letter
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

var newArr = []; // make a new array
for(var i=0; i < myarr.length; i++) {
    var splitit = myarr[i].split('-');  // split by -
    var capital0 = capitalizeFirstLetter(splitit[0].trim()); // trim the first word after split and capitalize the first letter
    var capital1 = capitalizeFirstLetter(splitit[1].trim()); // trim the second word after split and capitalize the first letter
    newArr.push('"'+capital0+':'+capital1+'"');   // push it to the new array with : instead of -  
}

alert(newArr); // alert new array

Working Demo

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28