JavaScript字符串查询替换算法挑战

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

第一个参数是将要对其执行查找和替换的字符串。

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

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

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

如果你被难住了,记得使用 Read-Search-Ask尝试与他人交流编程思路、但编写你自己的代码。

参考资料:

Array.prototype.splice()

String.prototype.replace()

Array.prototype.join()

function myReplace(str, before, after) {
var sArr=str.split(' ');
//判断before after是否为空
if(!before||!after)
{
 return '';
}
  
after=copyFirstCharType(before, after);
  
//拆分对话
for(var i=0;i<sArr.length;i++)
{
  if(sArr[i]===before)
  {
    sArr[i]=after;
  }
}
str=sArr.join(' ');
return str;
}

function copyFirstCharType(str1,str2)
{
  var charCodeForA='A'.charCodeAt(0);
  var charCodeForZ='Z'.charCodeAt(0);
  var charCodeFora='a'.charCodeAt(0);
  var charCodeForz='z'.charCodeAt(0);
  var arr1=str1.split('');
  var arr2=str2.split('');
  //单词首字母小写
  if(arr1[0].charCodeAt(0)>=charCodeFora&&arr1[0].charCodeAt(0)<charCodeForz){
    
    //单词首字母大写
    if(arr2[0].charCodeAt(0)>=charCodeForA&&arr2[0].charCodeAt(0)<charCodeForZ){
      
        arr2[0]=String.fromCharCode(arr2[0].charCodeAt(0)-charCodeForA+charCodeFora);
      
    }
      
  }
    //单词首字母大写
  else if(arr1[0].charCodeAt(0)>=charCodeForA&&arr1[0].charCodeAt(0)<charCodeForZ){
     //单词首字母小写
      if(arr2[0].charCodeAt(0)>=charCodeFora&&arr2[0].charCodeAt(0)<charCodeForz){
        
        arr2[0]=String.fromCharCode(arr2[0].charCodeAt(0)-charCodeFora+charCodeForA);
        
      }
  }
  str2=arr2.join('');
  return str2;
}



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

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”。

    原文作者:致学无忧
    原文地址: https://www.jianshu.com/p/4e9722f9f627
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞