js多层括号递归提取

正文开始

<p>字符串:</p><p>var aa='2'<br /></p><p>var str = "f {d + {c + { b+{aa} } 666 ";</p><p>第1步,提取第一个} .即  f {d + {c + { b+{aa}</p><p>第2步,替换最后一个{aa}  . 即  f {d + {c + { b+ 2 ;继续执行第一步<br /></p><p> </p><p><br /></p><p><pre>var matches = str.match(/{([^}]*?)}/g);// ["{id}", "{name}", "{1+2}"] var matchVal = ''; var resultStr = ''; var hasManyKuo = false; //替换多个括号 {fff{asds} => {fff123 function matchOne(str2) { if(typeof str2 =='object') str2 = str2[0]; var lastKuo = str2.lastIndexOf('{');// ["{id}", "{name}", "{1+2}"] if(lastKuo == -1) { return str2; } var reMatche = str2.slice(lastKuo); // {sf} var reMatchVal = reMatche.replace(/{|}/g, ''); var thisResult = ''; if(!isUndefined(data_[reMatchVal])) { thisResult = data_[reMatchVal]; } else { thisResult = eval(reMatchVal); } str2 = str2.replace(reMatche, thisResult); //{aaa{dadasd{cc} //再次判断是否还有最后的一组数据 var matchesReStr = str2.match(/{([^{]*?){([^}]*?)}/g); if(matchesReStr) { str2 = matchOne(matchesReStr); } return str2; } matches.forEach(function (match) { var manyRe = /{([^{]*?){([^}]*?)}/g; //{aaa{dadasd{cc} //过滤最后的一组数据 var matchesReStr = match.match(manyRe); if(matchesReStr) { match = matchOne(matchesReStr); str = str.replace(matchesReStr, match); hasManyKuo = true; return;//continue } matchVal = match.replace(/{|}/g, ''); if(!isUndefined(data_[matchVal])) { resultStr = data_[matchVal]; } else { resultStr = eval(matchVal); } str = str.replace(match, resultStr); }); //如果替换后 仍含有多个括号 { xxx } 继续替换 if(hasManyKuo) { str = filedStrToObj(str, data_, index); }</pre> <br /></p>

正文结束

js 正则替换返回值做回调函数 js按组提取括号里的变量