我试图获取下面数组中每个元素的第一个字母以返回大写字母,但似乎只能返回第二个字
var clenk = ["ham","cheese"];
var i = 0;
for (i = 0; i < clenk.length; i++) {
var result = clenk[i].replace(/\b./g, function(m){ return m.toUpperCase(); });
}
alert(result);
答案 0 :(得分:0)
String.prototype.toUpperCaseWords = function () {
return this.replace(/\w+/g, function(a){
return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
})
}
并使用它: -
"MY LOUD STRING".toUpperCaseWords(); // Output: My Loud String
"my quiet string".toUpperCaseWords(); // Output: My Quiet String
var stringVariable = "First put into a var";
stringVariable.toUpperCaseWords(); // Output: First Put Into A Var
答案 1 :(得分:0)
var clenk = ["ham","cheese"];
var i = 0;
for (i = 0; i < clenk.length; i++) {
var result = clenk[i].replace(/\b./g, function(m){ return m.toUpperCase(); });
alert(result);
}
将您的alert(result)
放入循环中,否则您只能获得最后一次result
。
答案 2 :(得分:0)
Array.prototype.map
可能更简单:
var results = clenk.map(function (word) {
return word.charAt(0).toUpperCase() + word.substr(1);
});