基于JavaScript实现的轻量级字符串占位符替换函数,占位符支持嵌套表达式,代码如下:
/*
* 占位符替换函数。占位符支持嵌套表达式,如a.b.c
* str:字串模板
* prefix:占位符前缀
* surfix:占位符后缀
* obj:数据对象
*/
function replaceHolder(str,prefix,surfix,obj){
var ret = '';
var p1=0,p2=0;
while(true){
p1 = str.indexOf(prefix,p2);
if(p1==-1) break;
if(p1>p2) ret+=str.substring(p2,p1);
p2 = str.indexOf(surfix,p1+prefix.length);
if(p2==-1) break;
var holder = str.substring(p1+prefix.length,p2);
var nests = holder.split('.');
var val = obj;
for(var i=0;i<nests.length;i++){
try{
val = val[nests[i]];
}catch(E){
alert("非法的属性表达式:"+holde