Skip to content Skip to sidebar Skip to footer

How To Capitalize First Letter And Lowercase The Rest Of The String

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, defaultMessage: 'Download

Solution 1:

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

functiontitleCase(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;
}
<pclass="capitalize-first">Download Price History</p>

Solution 2:

Using CSS:

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

Using JS:

constcapitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();

Solution 3:

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

export functiontitleCase(string) {
     returnstring[0].toUpperCase() + string.substr(1).toLowerCase()
}

Solution 4:

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';

Solution 5:

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();
}

Post a Comment for "How To Capitalize First Letter And Lowercase The Rest Of The String"