我是想把雙大括號裡的包括字串替換成真正的值,但是總是只能替換掉一個,不知道為什麼?
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 也支援正規表示式當作參數哦,給你改寫了一下
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
*/
如果執意要使用你原來的方式,需要取消掉全域參數g
rrreee某草草2017-06-05 11:15:51
RegExp物件,有個屬性,lastIndex,代表一個整數,標示開始下一次符合的字元位置。
。當exec第一次執行成功後,lastIndex為匹配項位置+1。正因為這樣,再次呼叫才會獲得下一個符合項。
回到你這個例子,第一次循環後,re的lastIndex為40,而此時tpl變為了tpl="/cube_xinbao_dial_result/1/{{query}}"
顯然你要匹配的query
的位置是在40之前的,所以再次匹配時失敗,exec返回null,循環跳出。
淡淡烟草味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));
輸出結果
/cube_xinbao_dial_result/1/223