Convert string to title case with JavaScript

后端 未结 30 2830
夕颜
夕颜 2020-11-21 06:40

Is there a simple way to convert a string to title case? E.g. john smith becomes John Smith. I\'m not looking for something complicated like John R

30条回答
  •  野的像风
    2020-11-21 07:41

    Here's my version, IMO it's easy to understand and elegant too.

    var str = "foo bar baz"
    
    console.log(
    
    str.split(' ')
       .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
       .join(' ')
    
    )
    // returns "Foo Bar Baz"

提交回复
热议问题