Search and Replace

function myReplace(str, before, after) {
/*
	思路
  //替换的值要符合原本的大小写状态
  //大小写状态,判断第一个值是否大写
  //charAt() 处理头字母的大小写,然后slice() 得到首字母以外的字符,最后拼接
*/
  if(before.search(/^[A-Z]/) === 0)//是否大小写
    after= after.charAt(0).toUpperCase()+ after.slice(1)//转成大写
  return str.replace(before, after);//替换
}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
//别人家的孩子
after = after[0].toUpperCase() + after.substr(1)

//别人家的孩子,妈呀大佬,是被碾压感觉
/*
String 增加把字符串首字母变大写方法
工具函数,可把字符串变成指定的姿势(大写、小写、首字母大写)
工具函数,得到字符串的姿势
*/

// 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);
}

//啊 啊  啊  啊 啊啊啊啊 啊,我好了
//这里暗含着对需求的理解,是解决问题吗?不只,还有