How to capitalize first letter and lowercase the rest of the string

后端 未结 5 1217
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-20 05:22

I am trying to capitalize the first letter of only the first word in a sentence.

This is the data in the tsx file { this.text({ id: downloadPriceHistory

相关标签:
5条回答
  • 2021-01-20 05:54

    try - make the rest of the string in lowercase as well.

    export function titleCase(string) {
         return string[0].toUpperCase() + string.substr(1).toLowerCase()
    }
    
    0 讨论(0)
  • 2021-01-20 06:06

    You only need to capitalize the first letter and concatenate that to the rest of the string converted to lowercase.

    function titleCase(string){
      return string[0].toUpperCase() + string.slice(1).toLowerCase();
    }
    console.log(titleCase('Download Price History'));

    This can also be accomplished with CSS by setting text-transform to lowercase for the entire element and using the ::first-letter pseudo element to set the text-transform to uppercase.

    .capitalize-first {
      text-transform: lowercase;
    }
    .capitalize-first::first-letter {
      text-transform: uppercase;
    }
    <p class="capitalize-first">Download Price History</p>

    0 讨论(0)
  • 2021-01-20 06:11

    Using CSS:

    p {
      text-transform: lowercase;
    }
    p::first-letter {
      text-transform: uppercase
    }
    

    Using JS:

    const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1).toLowercase();
    
    0 讨论(0)
  • 2021-01-20 06:12

    My suggestion is you get the first element of string and put in uppercase and get the rest of string and apply lowercase function.

    titleCase(string) {
      return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    }
    
    0 讨论(0)
  • 2021-01-20 06:15

    Why not just lowercase the entire string, and the uppercase just the first letter of the new string?

    function titleCase(string) {
        let sentence = string.toLowerCase();
        let titleCaseSentence = sentence.charAt(0).toUpperCase() + sentence.substring(1, sentence.length);
        return titleCaseSentence;
    }
    

    (Also, you're erasing your parameter to the function with that first line)

        string = 'hello World';
    
    0 讨论(0)
提交回复
热议问题