Capitalize the first letter of every word

前端 未结 8 1752
梦谈多话
梦谈多话 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(' ');
    
    }
    
    0 讨论(0)
  • 2020-12-09 18:18
    "tHiS iS a tESt".replace(/[^\s]+/g, function(str){ 
        return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
      });
    

    Other variant:

    "tHiS iS a tESt".replace(/(\S)(\S*)/g, function($0,$1,$2){ 
        return $1.toUpperCase()+$2.toLowerCase();
      });
    
    0 讨论(0)
提交回复
热议问题