繁体   English   中英

将每个单词的首字母大写,不能按预期工作

[英]Capitalizing first letter of every word, doesn't work as expected

首先,我知道这不是正确的做法,但我想了解为什么会这样,所以我会更好地理解这种语言。

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"

对于那种id的替换,而不是使用正则表达式

使用/\\b(.)/g作为第一个字母的模式,使用\\ U $ 0作为替换字符串,它应该按预期工作

这是一个小提琴

https://regex101.com/r/qQ2dE4/423

这将替换字符串中第一次出现的字符。 因此,较早位置的字符也可能被替换。

str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM