简体   繁体   中英

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.

Array.prototype.map may be simpler here:

var results = clenk.map(function (word) {
    return word.charAt(0).toUpperCase() + word.substr(1);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM