Convert string to title case with JavaScript

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

    var toMatch = "john w. smith";
    var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
          return i.toUpperCase() + (r != null ? r : "");
        }
    )
    

    Seems to work... Tested with the above, "the quick-brown, fox? /jumps/ ^over^ the ¡lazy! dog..." and "C:/program files/some vendor/their 2nd application/a file1.txt".

    If you want 2Nd instead of 2nd, you can change to /([a-z])(\w*)/g.

    The first form can be simplified as:

    function toTitleCase(toTransform) {
      return toTransform.replace(/\b([a-z])/g, function (_, initial) {
          return initial.toUpperCase();
      });
    }
    

提交回复
热议问题