为了实现字符串模板,借鉴Extjs字符串格式化实现:
版本1:
版本2:
版本3:
上述3中都是通过正则表达式实现,
参考:
[url]http://mustache.github.com/[/url]
版本1:
str = "abc:{name},cde:{code}";
String.prototype.format = function(obj){
if (arguments.length == 0) return '';
return this.replace(/\{[\w]*\}/g,function(match){
return obj[match.replace(/^\{|\}$/g,'')] || "\'\'";
});
}
str.format({name:'123',code:'456'}); // abc:123,cde:456
版本2:
str = "abc:{0},cde:{1}";
String.format = function(str){
if (arguments.length == 0) return '';
var param = Array.prototype.slice.call(arguments,1);
return str.replace(/\{[\w]*\}/g,function(match){
return param[match.replace(/^\{|\}$/g,'')] || "\'\'";
});
}
String.format(str,123,456); // abc:123,cde:456
版本3:
str = "abc:{name},cde:{code}";
String.format = function(str,obj){
if (arguments.length == 0) return '';
return str.replace(/\{[\w]*\}/g,function(match){
return obj[match.replace(/^\{|\}$/g,'')] || "\'\'";
});
}
String.format(str,{name:123,code:456}); // abc:123,cde:456
上述3中都是通过正则表达式实现,
参考:
[url]http://mustache.github.com/[/url]