简体   繁体   English

如何返回第一个字母为大写字母的数组的所有元素

[英]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

Source 资源

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.

相关问题 如何加入一个数组的元素,使得第一个字母是 JavaScript 中所有元素的大写? - How to join the elements of an array such that the first letter is capital for all elements in JavaScript? 如何验证名称中的每个第一个字母都是大写字母? - How do I validate that each first letter in a name is in capital letters? 我可以在javascript中使用大写字母吗 - Can I use Capital letter for in javascript 如何在javaScript数组中找到以某些字母开头的所有元素 - How can I find all the elements in javaScript array that start with certain letter 如何使这个 javascript 大写字段的所有首字母? - How can I make this javascript to capitilize all first letter of a field? 如何根据所包含属性的首字母过滤数组? - How can I filter an array based on the first letter of a contained property? 检查单词的第一个字母是否是大写字母 - Check if first letter of word is a capital letter 如何按元素首字母过滤 JavaScript 数组? - How can I filter a JavaScript array by element first letter? 使用 filter 方法检查数组每个元素的第一个字母是否大写。 但我不断得到整个数组 - Check if the first letter of each element of an array is capital using filter method. But I keep getting the whole array 将第一个字符大写字母添加到输入和数组(JavaScript) - Add First Char Capital Letter to input & array (Javascript)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM