Title case a sentence?

后端 未结 13 1457
醉梦人生
醉梦人生 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:55

    Here is a working piece of code. The problematic line in your code was this one:

    newstr[i].charAt(0).toUpperCase();
    

    That line gets the uppercased first letter of each word, but it doesn't do anything with it. The way the code below works is that it uppercases the first character, then appends the rest of the word, then assigns that back into newstr[i].

    function titleCase(str) {
      var newstr = str.split(" ");
      for(i=0;i<newstr.length;i++){
        newstr[i] = newstr[i].charAt(0).toUpperCase() + newstr[i].substring(1).toLowerCase();
      }
       newstr = newstr.join(" ");
       return newstr;
    }
    
    0 讨论(0)
提交回复
热议问题