Capitalize the first letter of every word

前端 未结 8 1781
梦谈多话
梦谈多话 2020-12-09 17:21

I want to use a javascript function to capitalize the first letter of every word

eg:

THIS IS A TEST ---> This Is A Test
this is a TEST ---> Th         


        
8条回答
  •  北海茫月
    2020-12-09 18:15

    This is a simple solution that breaks down the sentence into an array, then loops through the array creating a new array with the capitalized words.

     function capitalize(str){
    
      var strArr = str.split(" ");
      var newArr = [];
    
      for(var i = 0 ; i < strArr.length ; i++ ){
    
        var FirstLetter = strArr[i].charAt(0).toUpperCase();
        var restOfWord = strArr[i].slice(1);
    
        newArr[i] = FirstLetter + restOfWord;
    
      }
    
      return newArr.join(' ');
    
    }
    

提交回复
热议问题