gpt4 book ai didi

javascript - JS中数组语句首字母大写

转载 作者:行者123 更新时间:2023-12-03 07:16:40 24 4
gpt4 key购买 nike

我有一个数组,我想使用 map 将第一个字母转换为大写

const arrayTOCapital = [
'hi world',
'i want help ',
'change first letter to capital',

];

const arrayFirstLetterToCapital = () => {
return arrayTOCapital.map(function(x){ return
x.charAt(0).toUpperCase()+x.slice(1) })
}

输出应该是:

Hi World
I Want Help
Change First Letter To Capital

最佳答案

您可以只使用正则表达式 /\b\w/g 来查找所有以单词边界(例如空格)开头的字母并将其替换为大写版本

const arrayTOCapital = [
'hi world',
'i want help ',
'change first letter to capital',
];

console.log(arrayTOCapital.map(x => x.replace(/\b\w/g, c => c.toUpperCase())));

关于javascript - JS中数组语句首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63292341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com