将数组中每个单词的首字母大写

Capitalize first letters of every word in array

本文关键字:单词 数组      更新时间:2023-09-26

我有一个数组

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" ]

带两个" : "

但我想得到

[ "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));

在将"-"替换为":"后尝试此操作

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

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

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

要替换,请阅读

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