Convert string to title case with JavaScript

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

    I made this function which can handle last names (so it's not title case) such as "McDonald" or "MacDonald" or "O'Toole" or "D'Orazio". It doesn't however handle German or Dutch names with "van" or "von" which are often in lower-case... I believe "de" is often lower-case too such as "Robert de Niro". These would still have to be addressed.

    function toProperCase(s)
    {
      return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
              function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
    }
    

提交回复
热议问题