-1

I have an array

var my_array= [ "color - black", "color - light blue", "color - Red" ]

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

var my_array= [ "Color: Black", "Color:Light  Blue", "Color: Red" ]

And I try this

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

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

but it works only for

[ "Color: Black", "Color: Red" ]

and I get

 [ "Color:Light: Blue" ]

with two " : "

But I want to get

[ "Color:Light Blue" ]

var my_array= [ "color - black", "color - light blue", "color - Red" ]

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

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


document.write('<pre>'+JSON.stringify(my_array));
georg
  • 211,518
  • 52
  • 313
  • 390
Zarkoeleto
  • 133
  • 1
  • 2
  • 5

2 Answers2

2

Try this after replacing '-' to ':'

String.prototype.capitalize = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
1

To capitalize use when create array or when print array

function capitalizeFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

To replace read

http://www.w3schools.com/jsref/jsref_replace.asp

Michael
  • 1,089
  • 1
  • 11
  • 28