Convert string to title case with JavaScript

后端 未结 30 2836
夕颜
夕颜 2020-11-21 06:40

Is there a simple way to convert a string to title case? E.g. john smith becomes John Smith. I\'m not looking for something complicated like John R

30条回答
  •  独厮守ぢ
    2020-11-21 07:25

    If regex used in the above solutions is getting you confused, try this code:

    function titleCase(str) {
      return str.split(' ').map(function(val){ 
        return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
      }).join(' ');
    }
    

提交回复
热议问题