javascript - Why can this regular expression only replace one string? ?
仅有的幸福
仅有的幸福 2017-06-05 11:13:51
0
4
806

I want to replace the included strings in double curly brackets with real values, but I can only replace one. I don’t know why?

var tpl = '/cube_xinbao_dial_result/{{report_type}}/{{query}}'; var data = {report_type:1, query: '2323'} function render(tpl, data){ var re = /{{([^}]+)?}}/g; var match = ''; while(match = re.exec(tpl)){ tpl = tpl.replace(match[0],data[match[1]]); } return tpl; } console.log(render(tpl,data));
仅有的幸福
仅有的幸福

reply all (4)
遥远的她

ad

漂亮男人

String.replace also supports regular expressions as parameters, rewritten for you

var tpl = '/cube_xinbao_dial_result/{{report_type}}/{{query}}'; var data = {report_type:1, query: '2323'} function render(tpl, data){ var re = /{{([^}]+)?}}/g; return tpl.replace(re, function(
var tpl = '/cube_xinbao_dial_result/{{report_type}}/{{query}}'; var data = {report_type:1, query: '2323'} function render(tpl, data){ var re = /{{([^}]+)?}}/; //不要全局匹配就可以 var match = ''; while(match = re.exec(tpl)){ tpl = tpl.replace(match[0],data[match[1]]); } return tpl; } console.log(render(tpl,data)); /* /cube_xinbao_dial_result/1/2323 */
, , ){ if( in data ){ return data[]; }else{ return "[DATA."+ .toUpperCase() + "]"; //如果没有,提示标签错误 } }); } console.log(render(tpl,data)); /* /cube_xinbao_dial_result/1/2323 */ console.log(render(tpl,{query:1234})); /* /cube_xinbao_dial_result/[DATA.REPORT_TYPE]/1234 */

If you insist on using your original method, you need to cancel the global parameter g

rrreee
    某草草

    RegExp object has an attribute, lastIndex, which representsan integer, indicating the character position where the next matching begins.. When exec is executed successfully for the first time, lastIndex is the matching item position + 1. Because of this, calling it again will get the next match.
    Back to your example, after the first loop, the lastIndex of re is 40, and at this time tpl becomestpl="/cube_xinbao_dial_result/1/{{query}}"Obviously you want to match thequeryThe position is before 40, so it fails when matching again, exec returns null, and the loop jumps out.

      淡淡烟草味
      var tpl = '/cube_xinbao_dial_result/{{report_type}}/{{query}}'; var data = {report_type:1, query: '223'} function render(tpl, data){ var re = /{{([^}]+)?}}/g; var tpl2=tpl; tpl.match(re).forEach(function (val) { tpl2= tpl2.replace(val,data[val.substring(2,val.length-2)]); }); return tpl2; } console.log(render(tpl,data));

      Output results

      /cube_xinbao_dial_result/1/223
        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!