将数组

时间:2016-01-31 12:00:12

标签: javascript jquery

我有一个数组

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

我想要替换" - "用":"并将该数组中每个单词的第一个字母大写:

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, ":");
        }

但它仅适用于

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

我得到了

 [ "Color:Light: Blue" ]

有两个&#34; :&#34;

但我想得到

[ "Color:Light Blue" ]

&#13;
&#13;
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));
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

在更换&#39; - &#39;后尝试此操作到&#39;:&#39;

String.prototype.capitalize = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

答案 1 :(得分:1)

在创建数组或打印数组时使用大写

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

替换阅读

  

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

相关问题