【发布时间】:2020-02-22 15:29:47
【问题描述】:
我有一个函数应该将字符串中每个单词的第一个字母大写,但不知何故它提供了不正确的结果,知道为什么吗?我需要修复一下。
所以输入:hello dolly 输出:Hello Dolly。
空格计算正确,但大小写不正确。
function letterCapitalize(str) {
str = str.replace(str.charAt(0), str.charAt(0).toUpperCase());
let spaces = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === ' ') spaces.push(i);
}
for (let space of spaces) {
str = str.replace(str.charAt(space + 1), str.charAt(space + 1).toUpperCase());
}
return str;
}
console.log(letterCapitalize("hello there, how are you?"));
【问题讨论】:
-
我知道 replace 仅替换第一次出现,但我应该如何使其正常工作?
-
你的函数和
.toUpperCase()有什么区别? -
const letterCapitalize = x => x.toUpperCase(); -
const letterCapitalize = x => x.replace(/[a-zA-Z]/g, l => l.toUpperCase()) -
@Tibike 在字符类中不需要 A-Z,因为 OP 正在尝试更改为大写,所以 /[a-z]/ 就足够了
标签: javascript string