Convert string to title case with JavaScript

后端 未结 30 2891
夕颜
夕颜 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:27

    Most of these answers seem to ignore the possibility of using the word boundary metacharacter (\b). A shorter version of Greg Dean's answer utilizing it:

    function toTitleCase(str)
    {
        return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
    }
    

    Works for hyphenated names like Jim-Bob too.

提交回复
热议问题