大写数组中每个单词的第一个字母

时间:2016-01-28 16:50:59

标签: javascript jquery

我有一个数组

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

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

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);
}

但它仅适用于第一个单词

4 个答案:

答案 0 :(得分:5)

您可以使用另一个正则表达式在函数中为其大写字母交换字母。这样的事情会起作用:

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)

您可以在此处看到它:https://jsfiddle.net/igor_9000/c7tqraLo/ 最初的SO问题在这里:Capitalize words in string

答案 1 :(得分:2)

地图功能会为您处理。

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

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

答案 2 :(得分:1)

您可以映射数组并返回更改的项目

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>';

答案 3 :(得分:1)

你可以试试像

这样的东西
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

相关问题