You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript大小写匹配搜索替换:freeCodeCamp习题错误写法与正确实现

JavaScript字符串替换保留原匹配词首字母大小写实现

完成JavaScript「搜索与替换」习题时,需要实现对应替换规则:若原匹配词的首字母为大写,替换后的词汇首字母同步调整为大写;若原匹配词首字母为小写,替换后的词汇首字母同步调整为小写。

最初尝试通过正则判断原匹配词和替换词的首字母大小写,代码运行失败,错误实现如下:

function myReplace(str, before, after) {

  // 检查原匹配词和替换词的首字母是否为大写
  // 如果原词首字母大写、替换词首字母小写,将替换词首字母改为大写
  // 如果原词首字母小写、替换词首字母大写,将替换词首字母改为小写

  if (before[0] === (/^[A-Z]/) && after[0] !== (/^[A-Z]/)) {
     after = after.charAt(0).toUpperCase() + after.slice(1);
   } else if (before[0] !== (/^[A-Z]/) && after[0] === (/[^A-Z]/)) {
     after = after.charAt(0).toLowerCase() + after.slice(1);
   } 

  // 执行替换
 str = str.replace(before, after);

  return str;
}

// 测试用例1:应返回 "A quick brown fox leaped over the lazy dog"
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); 
// 测试用例2:应返回 "I think we should look down there"
myReplace("I think we should look up there", "up", "Down"); 

上述代码的问题在于:直接将单个字符与正则字面量做相等/不等判断,无法校验字符是否符合正则规则,导致所有条件分支都无法触发,功能失效。

后续调整了判断逻辑,改用「将首字母转大写后与原值比对」的方式判断字符是否为大写,代码可正常运行,正确实现如下:

function myReplace(str, before, after) {

  // 检查原匹配词和替换词的首字母是否为大写
  // 如果原词首字母大写、替换词首字母小写,将替换词首字母改为大写
  // 如果原词首字母小写、替换词首字母大写,将替换词首字母改为小写

  if (before.charAt(0) === before.charAt(0).toUpperCase()) {
    if(after.charAt(0) === after.charAt(0).toLowerCase()) {
      after = after.charAt(0).toUpperCase() + after.slice(1);
      str = str.replace(before, after)
    }
  } else {
    if(after.charAt(0) === after.charAt(0).toUpperCase()) {
      after = after.charAt(0).toLowerCase() + after.slice(1);
      str = str.replace(before, after)
    } else {
      str = str.replace(before, after)
    }
  }

  return str;
}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

内容的提问来源于stack exchange,提问作者Karen Hirayama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:45:03