首先,我知道这不是正确的做法,但我想了解为什么会这样,以便更好地理解语言。
function titleCase(str) {
let str1 = str.toLowerCase();
str1 = str1.replace(str1[0], str1[0].toUpperCase());
console.log(str1);
for(let i=1; i < str1.length; i++){
if(str1[i]===' '){
str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());
console.log(i);
console.log(str1);
}
}
return str1;
}
titleCase("ab cd ef gh ba");
所以,如果最后一个单词的第一个字母在它起作用之前没有出现在任何单词中的倒数第二个字母,“ab cd ef gh”在这里没问题,但“ab cd ef gh ba”会导致以下输出:“AB Cd Ef Gh ba”等。 谢谢!
最佳答案
发生这种情况的原因是 .replace()
函数将替换 第一个 出现的地方。
"Tell us more about your question us"
它第一次找到空格时,将替换第一次出现的小写字母“u”,恰好是正确的:
"Tell us more about your question us"
// ^ this "u" happens to be the first occurrence
但是当遇到最后一个单词“us”时,它会再次尝试找到第一个出现的小写字母“u”,也就是单词“about”中间的那个:
"Tell Us More About Your Question us"
// ^ this "u" is now the first lowercase "u"
关于javascript - 将每个单词的首字母大写,无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55367187/