【问题标题】:Using .toUpperCase to check for upper-caseness使用 .toUpperCase 检查大写
【发布时间】:2016-03-25 00:40:40
【问题描述】:

我的程序将字符串中的单词 '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”?

【问题讨论】:

  • 您似乎知道toUpperCase() 返回一个字符串,因为您执行afterCap = after[0].toUpperCase() + after.slice(1);。但是在这里您将其用作测试:if (before[0].toUpperCase())。你觉得toUpperCase 在这里返回什么?
  • 如果你只在if部分中使用afterCap而不在else中使用,那么在if中赋值,而不是之前。

标签: javascript


【解决方案1】:

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

您的代码实际上并没有检查第一个字母是否大写,只是将它们转换为大写并检查是否真实。如果字符串不为空则结果为真,第一个块将被执行,如果为空结果为空字符串,这是假的,什么都没有会被执行

javascript 中的真值是 除了 的所有值,false、0、null、undefined 和 NaN请参阅 MDN 文章 here 了解更多信息

改变这个

// 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 语句可以翻译成 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 可以返回空字符串,例如"".toUpperCase().
  • 空字符串也不真实。
  • @Oriol 感谢关注的是实际给定的代码而不是一般的代码,但应该注意到,为了清楚起见进行了更新
【解决方案2】:

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

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

【讨论】:

  • JS 没有字符。它们只是长度为 1 的字符串。
  • @smerny 看起来这是他检查的内容
  • @Oriol 确切地说,我只是不想造成任何混淆,因为他正在检查第一个字母是否为大写
猜你喜欢
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 2017-06-24
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
相关资源
最近更新 更多