Javascript 使用.toUpperCase检查上部外壳度

Javascript 使用.toUpperCase检查上部外壳度,javascript,Javascript,我的程序将字符串中的单词before替换为单词after。我想我可能用错了.toUpperCase和.toLowerCase。我可以使用.toUpperCase来检查上大小写,还是只能使用它来指定上大小写?我已经发布了我的短程序。这是彻底的评论,我期望它如何工作,然后与预期结果和实际结果 // Params are string, word to be removed, new word to replace removed word. function myReplace(str, befor

我的程序将字符串中的单词before替换为单词after。我想我可能用错了.toUpperCase和.toLowerCase。我可以使用.toUpperCase来检查上大小写,还是只能使用它来指定上大小写?我已经发布了我的短程序。这是彻底的评论,我期望它如何工作,然后与预期结果和实际结果

// Params are string, word to be removed, new word to replace removed word.
function myReplace(str, before, after) {
  var afterCap;
  var newString;

  // Uppercase first letter of after, add rest of word.
  // afterCap is then capitalized after.
  afterCap = after[0].toUpperCase() + after.slice(1);

  // If before is capitalized,
  if (before[0].toUpperCase()) {
    // Replace with capitalized after.
    newString = str.replace(before, afterCap);
  }

  // If before not-capitalized,
  else if (before[0].toLowerCase()) {
    // Replace with lowercase after.
    newString = str.replace(before, after);
  }

  console.log(newString);
}

myReplace("Let us go to the store", "store", "mall");

// Should return "Let us go to the mall"
// Is in fact returning "Let us go to the Mall"

为什么小写的单词“store”会被大写的“Mall”取代?

这是检查给定字符串(或字符)是否为大写的方法

function isUpperCase(str) {
    return str === str.toUpperCase();
}

toUppercase返回字符串,而不是布尔值

您的代码实际上并没有检查第一个字母是否为大写,只是将它们转换为大写并检查truthy是否正确。如果字符串不为空,则结果将为真,第一个块将执行,如果为空则结果将为空字符串,这是错误的,并且不会执行任何操作

javascript中的Truthy值都是值,除了false、0、null、undefined和NaN的值,有关详细信息,请参阅MDN文章

改变这个

// If before is capitalized,
if (before[0].toUpperCase()) {
// Replace with capitalized after.
    newString = str.replace(before, afterCap);
}
对此

// If before is capitalized,
if (before[0].toUpperCase() === before[0]) {
// Replace with capitalized after.
    newString = str.replace(before, afterCap);
}
第二条else-if语句可以转换为just-else,将代码转换为:

// If before is capitalized,
if (before[0].toUpperCase() === before[0]) {
    // Replace with capitalized after.
    newString = str.replace(before, afterCap);
} else {
    // If before not-capitalized,
    // Replace with lowercase after.
    newString = str.replace(before, after);
}
通过使用三元条件赋值运算符,可以进一步减少它

 newString = str.replace(before, 
                         before[0].toUppercase() === before[0] ? afterCap : after 
             );

您似乎知道
toUpperCase()
返回字符串,因为您在[0]之后执行
afterCap=after.slice(1)。但在这里,您将其用作测试:
if(在[0].toUpperCase()之前)
。您认为
toUpperCase
在这里返回什么?如果您只在
If
部分使用
afterCap
,而不在
else
中使用,则在
If
中分配值,而不是在.JS没有字符之前。它们只是长度为1的字符串。@smerny看起来是他检查的for@Oriol没错,我只是不想搞混,因为他正在检查第一个字母是否为大写
toUpperCase
可以返回空字符串,例如
“”。toUpperCase()
。空字符串也不是真实的。@Oriol thanks关注的是实际给定的代码,而不是一般的代码,但应该注意到,为了清晰起见,已进行了更新