Capitalize first letter of each word in JS

前端 未结 17 741
闹比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 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 ...'
    
    

提交回复
热议问题