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));
ad
String.replace also supports regular expressions as parameters, rewritten for you
If you insist on using your original method, you need to cancel the global parameter g
rrreeeRegExp 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 thequery
The position is before 40, so it fails when matching again, exec returns null, and the loop jumps out.Output results