Search code examples
javascriptchunks

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?


Solution

  • The map function is perfect for this.

    w[0].toUpperCase() : Use this to capitalize the first letter of each word

    w.slice(1): Return the string from the second character on

    EDGE Case

    If the user doesn't enter a string, the map function will not work and an error will be raised. This can be guarded against by checking if the user actually entered something.

    var userInput = prompt("Enter a string");
    
    var capitalizedString = userInput == "" ? "Invalid String" :
     userInput.split(/\s+/).map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
    
    console.log(capitalizedString);