算法基础1 - 搜索和替换

算法中级:搜索和替换

  1. 写一个字符串的搜索与替换函数,它的返回值为完成替换后的新字符串。
  2. 这个函数接收的第一个参数为待替换的句子。
  3. 第二个参数为句中需要被替换的单词。
  4. 第三个参数为替换后的单词。

注意:
需要保留被替换单词首字母的大小写格式。即如果传入的第二个参数为 “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) {
  // Find index where before is on string
  var index = str.indexOf(before);
  // Check to see if the first letter is uppercase or not
  if (str[index] === str[index].toUpperCase()) {
    // Change the after word to be capitalized before we use it.
    after = after.charAt(0).toUpperCase() + after.slice(1);
  }
  // Now replace the original str with the edited one.
  str = str.replace(before, after);
  return str;
}

方法二:

function myReplace(str, before, after) {
//Create a regular expression object
  var re = new RegExp(before,"gi");
//Check whether the first letter is uppercase or not
  if(/[A-Z]/.test(before[0])){
  //Change the word to be capitalized
    after = after.charAt(0).toUpperCase()+after.slice(1);
     }
     //Replace the original word with new one
  var  newStr =  str.replace(re,after);

 return newStr;
}

方法三:

function myReplace(str, before, after) {

    // create a function that will change the casing of any number of letter in parameter "target"
    // matching parameter "source"
    function applyCasing(source, target) {
        // split the source and target strings to array of letters
        var targetArr = target.split("");
        var sourceArr = source.split("");
        // iterate through all the items of sourceArr and targetArr arrays till loop hits the end of shortest array
        for (var i = 0; i < Math.min(targetArr.length, sourceArr.length); i++){
            // find out the casing of every letter from sourceArr using regular expression
            // if sourceArr[i] is upper case then convert targetArr[i] to upper case
            if (/[A-Z]/.test(sourceArr[i])) {
                targetArr[i] = targetArr[i].toUpperCase();
            }
            // if sourceArr[i] is not upper case then convert targetArr[i] to lower case
            else targetArr[i] = targetArr[i].toLowerCase();
        }
        // join modified targetArr to string and return
        return (targetArr.join(""));
    }

    // replace "before" with "after" with "before"-casing
    return str.replace(before, applyCasing(before, after));
}

方法四:

// Add new method to the String object, not overriding it if one exists already
String.prototype.capitalize =  String.prototype.capitalize ||
    function() {
        return this[0].toUpperCase() + this.slice(1);
    };

const Util = (function () {
// Create utility module to hold helper functions
    function textCase(str, tCase) {
        // Depending if the tCase argument is passed we either set the case of the
        // given string or we get it.
        // Those functions can be expanded for other text cases.
        
        if(tCase) {
            return setCase(str, tCase);
        } else {
            return getCase(str);
        }

        function setCase(str, tCase) {
            switch(tCase) {
                case "uppercase": return str.toUpperCase();
                case "lowercase": return str.toLowerCase();
                case "capitalized": return str.capitalize();
                default: return str;
            }
        }

        function getCase(str) {
            if (str === str.toUpperCase()) { return "uppercase"; }
            if (str === str.toLowerCase()) { return "lowercase"; }
            if (str === str.capitalize()) { return "capitalized"; }
            return "normal";
        }
    }

    return {
        textCase
    };
})();

function myReplace(str, before, after) {
    const { textCase } = Util;
    const regex = new RegExp(before, 'gi');
    const replacingStr = textCase(after, textCase(before));

    return str.replace(regex, replacingStr);
}

以上内容来源FCC

方法:

function myReplace(str, before, after) {
  let arr = str.split(' ').map((i)=>{
    if(i === before){
    let isCapital = (/[A-Z]/).test(i.slice(0,1));
      if(isCapital){
        return after.slice(0,1).toUpperCase().concat(after.slice(1))
      }else{
        return after;
      }
    }else{
      return i;
    }
  });
  return arr.join(' ')
}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值