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
try - make the rest of the string in lowercase as well.
export function titleCase(string) {
return string[0].toUpperCase() + string.substr(1).toLowerCase()
}
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>
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();
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();
}
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';