Capitalize first letter of each word in JS

前端 未结 17 632
闹比i
闹比i 2021-01-03 23:26

I\'m learning how to capitalize the first letter of each word in a string and for this solution I understand everything except the word.substr(1) portion. I see that it\'s a

17条回答
  •  花落未央
    2021-01-04 00:08

    The major part of the answers explains to you how works the substr(1). I give to you a better aproach to resolve your problem

       function capitalizeFirstLetters(str){
          return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
              return letter.toUpperCase();
          })
        }
    

    Explanation: - First convert the entire string to lower case - Second check the first letter of the entire string and check the first letter that have a space character before and replaces it applying .toUpperCase() method.

    Check this example:

    function capitalizeFirstLetters(str){
          return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
              return letter.toUpperCase();
          })
        }
    
    console.log(capitalizeFirstLetters("a lOt of words separated even   much spaces "))

提交回复
热议问题