[英]how can I return all the elements of an array with the first letter as a capital letter
I am trying to get the first letter of each element in the below array to return a capital letter but only seem to be able to return the second word 我正在尝试获取以下数组中每个元素的第一个字母以返回大写字母,但似乎只能返回第二个单词
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);
String.prototype.toUpperCaseWords = function () {
return this.replace(/\w+/g, function(a){
return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
})
}
and use it like :- 并像这样使用它:
"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
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);
}
Put your alert(result)
inside the loop, otherwise you're only getting the last result
out. 将您的alert(result)
放入循环中,否则您只会得到最后的result
。
Array.prototype.map
may be simpler here: Array.prototype.map
在这里可能更简单:
var results = clenk.map(function (word) {
return word.charAt(0).toUpperCase() + word.substr(1);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.