Capitalize first letter of each word in JS

前端 未结 17 745
闹比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-03 23:48

    const capitalize = str => {
      if (typeof str !== 'string') {
        throw new Error('Invalid input: input must of type "string"');
      }
    
      return str
        .trim()
        .replace(/ {1,}/g, ' ')
        .toLowerCase()
        .split(' ')
        .map(word => word[0].toUpperCase() + word.slice(1))
        .join(' ');
    };
    
    • sanitize the input string with trim() to remove whitespace from the leading and trailing ends
    • replace any extra spaces in the middle with a RegExp

    • normalize and convert it all toLowerCase() letters

    • convert the string to an array split on spaces

    • map that array into an array of capitalized words

    • join(' ') the array with spaces and return the newly capitalized string

提交回复
热议问题