如何大写第一个字母并小写字符串的其余部分 [英] 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.
这是tsx文件中的数据{this.text({id: downloadPriceHistory
,defaultMessage:'Download Price History'})}上面显示的ID来自数据库,可以多种形式发送到api.
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"
.
推荐答案
您只需要将首字母大写并将其连接到转换为小写字母的其余字符串上即可.
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'));
这也可以通过CSS来实现,方法是将整个元素的 text-transform
设置为小写
,并使用 :: first-letter
将 text-transform
设置为 uppercase
的伪元素.
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>
这篇关于如何大写第一个字母并小写字符串的其余部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!