需求:javascript
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 }