使用.toUpperCase检查上部平齐度
Using .toUpperCase to check for upper-caseness
我的程序将字符串中的单词"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返回字符串,而不是布尔值
您的代码实际上并没有检查第一个字母是否为大写,只是将它们翻译成大写并检查是否为真。如果字符串不是空的,则结果将是真的,并且第一个块将被执行,如果它是空的则结果将是空字符串,这是错误的,并且什么都不执行
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语句可以翻译成其他语句,将您的代码转换为以下内容:
// 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
);
这是检查给定字符串(或字符)是否为大写的方法
function isUpperCase(str) {
return str === str.toUpperCase();
}
相关文章:
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 在单击任何位置时隐藏元素,而不检查每次DOM单击
- 如何检查管道中未定义的项目
- 主干-不管怎样,检查事件以前是否绑定过
- 使用javascript检查多个输入值,并在1次检查中标记多个输入框
- 递归使用 eval() 是检查程序执行的好方法吗?
- 检查onsubmit doenst work jquery contactform上的函数
- JavaScript 检查隐藏字段中的值并将其设置为隐藏字段值
- API密钥使用和检查示例
- 如何让程序检查所选单词中是否有按键
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 用于检查数组中是否存在元素的javascript自定义方法
- 如何检查字符串的一部分与数组匹配
- Jquery如何检查今天的时间大于使用给定时间
- 使用javascript反复检查用户在facebook上的登录状态
- 使用 jQuery 检查所有值是否为空或已填充
- 使用Javascript使用数组检查文本框中的值
- JavaScript代码未正确检查ajax请求
- 如何检查用户在html5视频播放器中观看了完整的视频
- 使用.toUpperCase检查上部平齐度