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));
漂亮男人2017-06-05 11:15:51
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某草草2017-06-05 11:15:51
RegExp object has an attribute, lastIndex, which represents an 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 becomes tpl="/cube_xinbao_dial_result/1/{{query}}"
Obviously you want to match the query
The position is before 40, so it fails when matching again, exec returns null, and the loop jumps out.
淡淡烟草味2017-06-05 11:15:51
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