gpt4 book ai didi

javascript - JS中每个单词首字母大写

转载 作者:可可西里 更新时间:2023-11-01 01:35:45 30 4
gpt4 key购买 nike

我正在学习如何将字符串中每个单词的首字母大写,对于这个解决方案,我理解除了 word.substr(1) 部分之外的所有内容。我看到它添加了损坏的字符串,但 (1) 是如何工作的?

function toUpper(str) {
return str
.toLowerCase()
.split(' ')
.map(function(word) {
return word[0].toUpperCase() + word.substr(1);
})
.join(' ');
}
console.log(toUpper("hello friend"))

最佳答案

返回值包含两部分:

return word[0].toUpperCase() + word.substr(1);

1) word[0].toUpperCase(): 第一个大写字母

2) word.substr(1) 除了第一个字母被大写外,其余的都是单词。这是关于如何 substr 的文档有效。

如果要调试,请引用下面的结果:

function toUpper(str) {
return str
.toLowerCase()
.split(' ')
.map(function(word) {
console.log("First capital letter: "+word[0]);
console.log("remain letters: "+ word.substr(1));
return word[0].toUpperCase() + word.substr(1);
})
.join(' ');
}
console.log(toUpper("hello friend"))

关于javascript - JS中每个单词首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42755664/

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