Skip to content

Instantly share code, notes, and snippets.

@GeekaholicLin
Created August 11, 2017 03:45
Show Gist options
  • Save GeekaholicLin/025f146d859141d9df219d1ec56a3f71 to your computer and use it in GitHub Desktop.
Save GeekaholicLin/025f146d859141d9df219d1ec56a3f71 to your computer and use it in GitHub Desktop.
replace the nested matched string
var val = '<blockquote><p>pppp[id.]pppp</p><h1>h1h1[id.]h1h1</h1></blockquote><p>pppp[id.]ppppp</p>';
var re = /<(blockquote|p|h1)>(([^]*?)\[\id\.\]([^]*?))<\/\1>/g;
function recMatch(content,re){
	content = content.replace(re,function(match,p1,p2,p3,p4){
    var matchedChild = p2;
    //如果child依然匹配,递归调用
  	if(re.test(p2)){
      matchedChild = recMatch(matchedChild,re);
      //matchedChild已经是处理过后的,直接拼接返回即可
      return '<'+p1+'>'+matchedChild+'</'+p1+'>';
    }else{
      //一旦不匹配,进行处理,返回替换匹配match的值
      return '<'+p1+' title="'+p3+'" >'+p4+'</'+p1+'>';
    }
    //返回的目的是replace匹配的值
  });
  //返回最终的结果
  return content;
}
var result = recMatch(val,re);
console.log(result);
//logs: <blockquote><p title="pppp" >pppp</p><h1 title="h1h1" >h1h1</h1></blockquote><p title="pppp" >ppppp</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment