使用原生js實現replace()函數

需求:

let str = 'zhufeng2019zhufeng2019'
str = str.replace(/zhufeng/g, function(...args){
    // args中存儲了每一次大正則匹配的信息和小分組匹配的信息: content, $1, $2
    return '@' // 返回的是啥就把當前正則匹配的內容替換成啥
})    
    String.prototype.replace = function (regexp, callback) {
      let arr = this.match(regexp)
      let content = arr[0]
      let newStr = this
      let $2 = this.toString()


      for (let i = 0; i < arr.length; i++) {
        let $1 = newStr.indexOf(content)
        let str = callback(content, $1, $2)
        if ($1 === 0) {
          newStr = str + newStr.slice(content.length)
        } else {
          newStr = newStr.slice(0, $1) + str + newStr.slice($1 + content.length)
        }
      }
      return newStr
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章