Lodash title case (uppercase first letter of every word)

前端 未结 13 1657
萌比男神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:38

    This can be done with only lodash

    properCase = string =>
            words(string)
                .map(capitalize)
                .join(' ');
    
    const proper = properCase('make this sentence propercase');
    
    console.log(proper);
    //would return 'Make This Sentence Propercase'
    
    0 讨论(0)
  • 2021-01-30 19:40

    Below code will work perfectly:

    var str = "TITLECASE";
    _.startCase(str.toLowerCase());
    
    0 讨论(0)
  • 2021-01-30 19:41

    There are mixed answers to this question. Some are recommending using _.upperFirst while some recommending _.startCase.

    Know the difference between them.

    i) _.upperFirst will transform the first letter of your string, then string might be of a single word or multiple words but the only first letter of your string is transformed to uppercase.

    _.upperFirst('jon doe')

    output:

    Jon doe

    check the documentation https://lodash.com/docs/4.17.10#upperFirst

    ii) _.startCase will transform the first letter of every word inside your string.

    _.startCase('jon doe')

    output:

    Jon Doe

    https://lodash.com/docs/4.17.10#startCase

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

    with lodash version 4.

    _.upperFirst(_.toLower(str))

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

    Here's a way using ONLY lodash methods and no builtin methods:

    _.reduce(_.map(_.split("Hello everyOne IN the WOrld", " "), _.capitalize), (a, b) => a + " " + b)
    
    0 讨论(0)
  • 2021-01-30 19:44

    Here's another solution for my use case: "devil's backbone"

    Simply:

    function titleCase (str) {
      return _.map(str.split(' '), _.upperFirst).join(' ');
    }
    

    Using startCase would remove the apostrophe, so I had to work around that limitation. The other solutions seemed pretty convoluted. I like this as it's clean, easy to understand.

    0 讨论(0)
提交回复
热议问题