Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalizing a String

I'm aware of the CSS attribute text-transform: capitalize but can anyone help me with replicating this using Javascript?

I would like to pass an argument to my function which will return the string with the first letter of each word capitalized.

I've got this far but I'm stuck trying to break my array of strings in to chunks:

function upper(x){
  x = x.split(" "); 

  // this function should return chunks but when called I'm getting undefined
  Array.prototype.chunk = function ( n ) {
      return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
  };

  x = x.chunk;

}

upper("chimpanzees like cigars")

after the chunk I'm guessing I need to again split each chunk in to the first character and the remaining characters, use .toUpperCase() on the first character, join it back up with the remaining and then join up the chunks again in to a string?

Is there a simpler method for doing this?


1 Answers

I came up with a solution for both a single word and also for an array of words. It will also ensure that all other letters are lowercase for good measure. I used the Airbnb style guide as well. I hope this helps!

const mixedArr = ['foo', 'bAr', 'Bas', 'toTESmaGoaTs'];
const word = 'taMpa';

function capitalizeOne(str) {
  return str.charAt(0).toUpperCase().concat(str.slice(1).toLowerCase());
}


function capitalizeMany(args) {
  return args.map(e => {
    return e.charAt(0).toUpperCase().concat(e.slice(1).toLowerCase());
  });
};

const cappedSingle = capitalizeOne(word);
const cappedMany = capitalizeMany(mixedArr);

console.log(cappedSingle);
console.log(cappedMany);
like image 183
Rick Mottola Avatar answered Feb 24 '26 11:02

Rick Mottola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!