var templateStr = "我的名字叫<%=name%>我是一只小狗,今年<%=age%>岁。";
var data = {
name:'旺财',
age:'18'
};
/*会利用正则来匹配*/
//console.log(/<%=\s*([^%>]+\S)\s*%>/.exec(templateStr));
var match = /<%=\s*([^%>]+\S)\s*%>/.exec(templateStr);
console.log(match);//['<%=name%>',name,....]
//match[1]--->name match[0]----><%=name%>
//data[match[1]]-->'旺财'
//即将<%=name%> 用 '旺财' 进行替换
templateStr = templateStr.replace(match[0],data[match[1]]);
console.log(templateStr);
match = /<%=\s*([^%>]+\S)\s*%>/.exec(templateStr);
console.log(match);
templateStr = templateStr.replace(match[0],data[match[1]]);
console.log(templateStr);
/*while循环实现将字符串中的所有内容替换掉掉*/
//匹配到<%=XX%>
var match = /<%=\s*([^%>]+\S)\s*%>/.exec(templateStr);
while(match){//match有值
templateStr = templateStr.replace(match[0],data[match[1]]);//替换
match = /<%=\s*([^%>]+\S)\s*%>/.exec(templateStr);//继续匹配<%=XX%>
}
console.log(templateStr);
//原理!!
/*apply 改变函数的上下文当中的this的指向*/
template.apply({name:'xgg'},['xgg','10']);
/*也是一个方法也是一个函数*/
var template = new Function('templateStr','data',
'var match = /<%=\s*([^%>]+\S)\s*%>/.exec(templateStr);while(match)
{templateStr = templateStr.replace(match[0],data[match[1]]);
match = /<%=\s*([^%>]+\S)\s*%>/.exec(templateStr)}console.log(templateStr);');
template(templateStr,data);
var template = new Function('name','age','代码块');