Search and Replace

题目

使用给定的参数对句子执行一次查找和替换,然后返回新句子。

第一个参数是将要对其执行查找和替换的句子。

第二个参数是将被替换掉的单词(替换前的单词)。

第三个参数用于替换第二个参数(替换后的单词)。

注意:替换时保持原单词的大小写。例如,如果你想用单词 “dog” 替换单词 “Book” ,你应该替换成 “Dog”。

要求

    Array.splice()

    String.replace()

    Array.join()

    String.toUpperCase()

    String.charCodeAt()

    String.substring

    myReplace("Let us go to the store", "store", "mall") 应该返回 "Let us go to the mall"。

    myReplace("He is Sleeping on the couch", "Sleeping", "sitting") 应该返回 "He is Sitting on the couch"。

    myReplace("This has a spellngi error", "spellngi", "spelling") 应该返回 "This has a spelling error"。

    myReplace("His name is Tom", "Tom", "john") 应该返回 "His name is John"。

    myReplace("Let us get back to more Coding", "Coding", "algorithms") 应该返回 "Let us get back to more Algorithms"

代码

function myReplace(str, before, after) {
  var arr = str.split(" ");
  for(var i = 0; i < arr.length; i++) {
    if(arr[i] == before) {
      if(before.charCodeAt(0) >= 65 && before.charCodeAt(0) <= 90) {
        after = after[0].toUpperCase() + after.substring(1,after.length);
      }
      arr.splice(i,1,after);   
    }
  }
  str = arr.join(" ");
  return str;
}

function otherReplace(str,before,after) {
  var re = "/" + before + "/g";
  if(before.charCodeAt(0) >= 65 && before.charCodeAt(0) <= 90) {
    after = after[0].toUpperCase() + after.substring(1,after.length);
  }
  str = str.replace(re,after);
  return str;
}

myReplace("He is Sleeping on the couch", "Sleeping", "sitting");
otherReplace("He is Sleeping on the couch", "Sleeping", "sitting");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值