const replaceIterator = ( content, pattern, replacement )=>{
let index = 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;
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(""))
标签:index,arr,遍历,res,js,content,start,push,替换 From: https://www.cnblogs.com/laremehpe/p/18046825