Convert camelCaseText to Sentence Case Text

后端 未结 20 2212
闹比i
闹比i 2020-11-28 03:44

How can I convert a string either like \'helloThere\' or \'HelloThere\' to \'Hello There\' in JavaScript?

20条回答
  •  一个人的身影
    2020-11-28 04:29

    Based on one of the examples above I came up with this:

    const camelToTitle = (camelCase) => camelCase
      .replace(/([A-Z])/g, (match) => ` ${match}`)
      .replace(/^./, (match) => match.toUpperCase())
      .trim()
    

    It works for me because it uses .trim() to handle the edge case where the first letter is capitalized and you end up with a extra leading space.

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

提交回复
热议问题