Title case a sentence?

后端 未结 13 1449
醉梦人生
醉梦人生 2021-02-10 01:27

I\'m trying to proper case a string in javascript - so far I have this code: This doesn\'t seem to capitalize the first letter, and I\'m also stuck on how to lowercase all the l

13条回答
  •  醉话见心
    2021-02-10 01:35

    One of the cleanest ways I can come up with, using ES6, while still lacking a proper .capitalize() string prototype method:

    let sent = "these are just some words on paper"
    sent.split(' ').map ( ([h, ...t]) => h.toUpperCase() + t.join('').toLowerCase() )
    

    Uses destructuring on array element strings to obtain head and tail via spread operator (making tail a sequence of characters) which are first joined before coerced to lower case. Or you could replace that with a s => s[0].toUpperCase() + s.substring(1).toLowerCase() I guess. Oh, since the question seems to indicate ES5, transformation is cheap although noticeably more verbose:

    function capitalize (sentence) {
        return sentence.split(' ').map(
            function (s) {
                return s[0].toUpperCase() + s.substring(1).toLowerCase()      
            }).join(' ') ;
    }
    

    That is, assuming you'd want another sentence returned.

提交回复
热议问题