Lodash title case (uppercase first letter of every word)

前端 未结 13 1659
萌比男神i
萌比男神i 2021-01-30 19:25

I\'m looking through the lodash docs and other Stack Overflow questions - while there are several native JavaScript ways of accomplishing this task, is there a way I can convert

相关标签:
13条回答
  • 2021-01-30 19:47
    'This string ShouLD be ALL in title CASe'
      .split(' ')
      .map(_.capitalize)
      .join(' ');
    
    0 讨论(0)
  • 2021-01-30 19:50

    This can be done with a small modification of startCase:

    _.startCase(_.toLower(str));
    

    console.log(_.startCase(_.toLower("This string ShouLD be ALL in title CASe")));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

    0 讨论(0)
  • 2021-01-30 19:53

    Not as concise as @4castle's answer, but descriptive and lodash-full, nonetheless...

    var basicTitleCase = _
        .chain('This string ShouLD be ALL in title CASe')
        .toLower()
        .words()
        .map(_.capitalize)
        .join(' ')
        .value()
    
    console.log('Result:', basicTitleCase)
    console.log('Exact Match:' , basicTitleCase === 'This String Should Be All In Title Case')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

    0 讨论(0)
  • 2021-01-30 19:55
    const titleCase = str =>
      str
        .split(' ')
        .map(str => {
          const word = str.toLowerCase()
          return word.charAt(0).toUpperCase() + word.slice(1)
        })
        .join(' ')
    

    You can also split out the map function to do separate words

    0 讨论(0)
  • 2021-01-30 19:56
     var s = 'This string ShouLD be ALL in title CASe';
     _.map(s.split(' '), (w) => _.capitalize(w.toLowerCase())).join(' ')
    

    Unless i missed it, lodash doesnt have its own lower/upper case methods.

    0 讨论(0)
  • 2021-01-30 19:57
    _.startCase(_.camelCase(str))
    

    For non-user-generated text, this handles more cases than the accepted answer

    > startCase(camelCase('myString'))
    'My String'
    > startCase(camelCase('my_string'))
    'My String'
    > startCase(camelCase('MY_STRING'))
    'My String'
    > startCase(camelCase('my string'))
    'My String'
    > startCase(camelCase('My string'))
    'My String'
    
    0 讨论(0)
提交回复
热议问题