Skip to content

重写String.prototype.replace() 1.正则在字符串中匹配几次,回调函数就会被执行几次(前提是正则设置了全局修饰符g) 2.每一次执行回调函数,都把当前正则信息(大正则,小分组)传递给回调函数 3.还要接收回调函数的返回值,返回结果是什么就要把当前字符串正则匹配的内容替换成返回值

js
String.prototype._replace = function (reg, callback) {
  let isGlobal = reg.global,
    _this = this

  let arr = reg.exec(this)

  // 替换字符串内容
  function handle () {

  }
  while (arr) {
    // 每次匹配成功都要执行回调函数并接收回调返回值,替换原字符串中正则匹配的内容
    if (typeof callback === 'function') {
      // [ '{0}', '0', index: 0, input: '{0}年{1}月{2}日', groups: undefined ]
      // 通过大正则匹配内容长度和index的配合准确替换字符串
      // _this是替换后的字符串
      let res = callback(...arr),  // 回调函数返回值(被替换成的值)
        index = _this.indexOf(arr[0]), // 大正则匹配内容(被替换内容)在_this中的下标
        left = _this.substr(0, index), // 被替换内容左部分
        right = _this.substr(index + arr[0].length) // 被替换内容右部分
      _this = left + res + right // 替换
    }
    // 没有设置global,只匹配一次
    if (!isGlobal) break
    arr = reg.exec(this)
  }
  return _this
}

let str = '{0}年{1}月{2}日',
  arr = ['2021', '10', '9']
const result = str._replace(/\{(\d)\}/g, (_, $1) => {
  return '@'
})
console.log(result)