how can I return all the elements of an array with the first letter as a capital letter

144 Views Asked by At

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

There are 3 best solutions below

1
On
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

0
On
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.

0
On

Array.prototype.map may be simpler here:

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