user9179227
user9179227

Reputation: 33

Return String by capitalizing every first letter of the each word and rest in lower case

I split the string at ’ ’ and store all the words in in strSplit. The used FORLOOP for capitalizing first letter of every word to capitalize and stored in variable firstLetter. Stored rest of the word in variable restLetter. Then use + to add firstLetter and restLetter and stored this result in newLetter. Now i want to use join to take away “” form each word so that it becomes a one string with every first letter capitalized in each word. but my if i applied join on newLetter it is not working.

    function titleCase(str) {
     var strSplit = (str.split(' '));
     var newLetter = [];
     var returnString;
     var firstLetter;
     var restLetter;
       for(i=0; i <=(strSplit.length-1); i++){
        firstLetter = strSplit[i].charAt(0).toUpperCase();
        for(i=0; i <=(strSplit.length-1); i++){
        firstLetter = strSplit[i].charAt(0).toUpperCase();    
        restLetter = strSplit[i].slice(1, str.Split);    
        newLetter = firstLetter + restLetter;
        newLetter.join(" and ");

      }  
     return newLetter;
   }
   }

   titleCase("I'm a little tea pot");

Upvotes: 1

Views: 532

Answers (2)

user9179227
user9179227

Reputation: 33

I found the solution myself with same approach i started!! Here it is:

   function titleCase(str) {
    var strSplit = (str.split(' '));
    var newLetter = [];   
    var firstLetter;
    var restLetter;
     for(i=0; i <strSplit.length; i++){
      firstLetter = strSplit[i].charAt(0).toUpperCase();        
      restLetter = strSplit[i].slice(1, str.Split).toLowerCase();    
      newLetter.push(firstLetter + restLetter);           
     }  
    return newLetter.join(" ");
  }
  titleCase("I'm a little tea pot");

Upvotes: 0

mdatsev
mdatsev

Reputation: 3879

You can easily do it like this:

function titleCase(str) {
  return str.split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(' ')

}

console.log(titleCase("I'm a little tea pot"));

Here we split by space then we make each word start with uppercase by using map and then concatenating the first character to uppercase and the rest of the word lowercase, and then join the words array with space.

Upvotes: 2

Related Questions