Capitalize first letter of each word in JS

前端 未结 17 631
闹比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 "))

    0 讨论(0)
  • 2021-01-04 00:08

    The regexp /\b\w/ matches a word boundary followed by a word character. You can use this with the replace() string method to match then replace such characters (without the g (global) regexp flag only the first matching char is replaced):

    > 'hello my name is ...'.replace(/\b\w/, (c) => c.toUpperCase());
    'Hello my name is ...'
    > 'hello my name is ...'.replace(/\b\w/g, (c) => c.toUpperCase());
    'Hello My Name Is ...'
    
    
    0 讨论(0)
  • 2021-01-04 00:11

    Consider an arrow function with an implicit return:

    word => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}` 
    

    This will do it in one line.

    0 讨论(0)
  • 2021-01-04 00:11

    Using ES6

    let captalizeWord = text => text.toLowerCase().split(' ').map( (i, j) => i.charAt(0).toUpperCase()+i.slice(1)).join(' ')
    
    captalizeWord('cool and cool')
    
    0 讨论(0)
  • 2021-01-04 00:14
    function toTitleCase(str)
    {
      return str.replace(/\w\S*/g, function(txt){return 
      txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    }
    
    0 讨论(0)
提交回复
热议问题