const replaceIterator = ( content, pattern, replacement )=>{

  let index = 0, start = 0;
  let arr = [];
  
  while(true){
      const res = content.match(pattern);
      if(res === null){ 
        if(content.length){
          arr.push(content);
        }
        break;
      }
      start = res.index;
      start && arr.push(content.substring(0,start));
      arr.push(replacement.replace('$',index++));
      content = content.substring(start + res[0].length);
  }

  return arr;
}
console.log(replaceIterator('2112',/1/,'x$x')) 
/*
[
    "2",
    "x0x",
    "x1x",
    "2"
]
*/

升级:

const finder = ( content, pattern, callback )=>{
    let index = 0, start = 0;
    let arr = [];
    
    while(true){
      const res = content.match(pattern);
        if(res === null){ 
          if(content.length){
            arr.push(content);
          }
          break;
        }
      start = res.index;
      start && arr.push(content.substring(0,start));
      arr.push(callback(res[0], index++));
      content = content.substring(start + res[0].length);
    }

  return arr;
}


console.log(finder('123456', /1/, text=>{
    return 'a'
}).join(""))

 

 posted on 2024-03-02 15:42  laremehpe  阅读(14)  评论(0编辑  收藏  举报