简体   繁体   中英

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

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.

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

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