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 Price History' }) }
the id shown above comes from the database where it could be send to the api in various forms.
I have tried to use this logic below:
export function titleCase(string) {
string = 'hello World';
const sentence = string.toLowerCase().split('');
for (let i = 0; i < sentence.length; i++) {
sentence[i] = sentence[i][0].toUpperCase() + sentence[i];
}
return sentence;
}
For example, for the input "Download Price History"
, the result should be "Download price history"
.
string: A string in which you want to capitalize only the first letter of the first word and lowercase the rest. This formula uses the UPPER, LEFT, RIGHT, LOWER and LEN functions to uppercase only the first letter of the first word and lowercase the rest in a string.
This formula uses the UPPER, LEFT, RIGHT, LOWER and LEN functions to uppercase only the first letter of the first word and lowercase the rest in a string.
Use the charAt () method to get the first letter of the string. Call the toUpperCase () method on the letter. Use the slice () method to get the rest of the string. Concatenate the results. Copied! The first example in the code snippet converts the first letter of the string to uppercase and leaves the rest as is.
We can apply this command as follows: As you can see based on the output of the RStudio console, the toTitleCase function converted some but not all first letters to uppercase. The words “this” and “is” where kept in lower case. Whether you prefer to capitalize all or just some letters is a matter of style.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With