算法:搜索和替换(learn to code at freeCodeCamp)

题目

算法中级:搜索和替换

在这道题目中,我们需要写一个字符串的搜索与替换函数,它的返回值为完成替换后的新字符串。

这个函数接收的第一个参数为待替换的句子。

第二个参数为句中需要被替换的单词。

第三个参数为替换后的单词。

注意:
你需要保留被替换单词首字母的大小写格式。即如果传入的第二个参数为 “Book”,第三个参数为 “dog”,那么替换后的结果应为 “Dog”

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) {
    
    
  let reg = /^[A-Z]/;
  let index = str.indexOf(before);
  let newAfter = "";
  if (reg.test(before)) {
    
    
    // newAfter = after[0].toUpperCase() + after.slice(1);
    newAfter = after.replace(/\b\w+\b/g,
      function (word) {
    
    
        return word.substring(0, 1).toUpperCase() + word.substring(1);
      })
  } else {
    
    
    newAfter = after
  }

  if (index != -1) {
    
    
    return str.slice(0, index) + newAfter + str.slice(index + before.length);

  } else {
    
    
    return str;
  }

}

myReplace("He is Sleeping on the couch", "Sleeping", "sitting");

おすすめ

転載: blog.csdn.net/weixin_43245095/article/details/115111739