转载自: http://www.cnblogs.com/sohighthesky/archive/2011/03/28/string_buf.html
用字符串连接的类,把以前的方法写成了类的方式,方便调用 ,
支持实例调用 和静态调用
参数可以是单独的字符串,或者json的格式,或者类似参数数组的方式,见下面示例
/*
* @author: uedsky
* @version: 1.0
*/
/**
* @class String concat
* @return {StrBuf/String}
* @constructor
*/
var StrBuf = function(s) {
this.data = [];
if(s) {
var args = arguments, buf;
if(this instanceof StrBuf){
this.push.apply(this, args);
}else{// static invoke
buf = new StrBuf();
buf.push.apply(buf, args);
return buf.toString();
}
}
};
StrBuf.prototype = {
// add String to the instance
push: function(s, j){
var args = arguments;
if(args.length < 2) {
this.data.push(s || "");
}else if(typeof j == 'object'){
this.data.push(s.replace(/\$\{([\w.]+)}/g, function($, $1){
return ($1 in j) ? j[$1] : $;
}));
}else {
this.data.push(s.replace(/\{(\d+)}/g, function($, $1){
return args[+$1 + 1];
}));
}
},
toString: function(){
return this.data.join("");
}
};
* @version: 1.0
*/
/**
* @class String concat
* @return {StrBuf/String}
* @constructor
*/
var StrBuf = function(s) {
this.data = [];
if(s) {
var args = arguments, buf;
if(this instanceof StrBuf){
this.push.apply(this, args);
}else{// static invoke
buf = new StrBuf();
buf.push.apply(buf, args);
return buf.toString();
}
}
};
StrBuf.prototype = {
// add String to the instance
push: function(s, j){
var args = arguments;
if(args.length < 2) {
this.data.push(s || "");
}else if(typeof j == 'object'){
this.data.push(s.replace(/\$\{([\w.]+)}/g, function($, $1){
return ($1 in j) ? j[$1] : $;
}));
}else {
this.data.push(s.replace(/\{(\d+)}/g, function($, $1){
return args[+$1 + 1];
}));
}
},
toString: function(){
return this.data.join("");
}
};
调用 示例如下:
var buf = new StrBuf("contructor str\n");
buf.push("hello,");
buf.push("Today is {0}, {1}", "Monday", "March 28th");
buf.push("${name} is a good ${category} company", {name: "Google", category: "Intenet"});
document.write(buf);// auto call toString method
console.log(buf);
console.log(StrBuf("static {0} method", "invoke"));
buf.push("Today is {0}, {1}", "Monday", "March 28th");
buf.push("${name} is a good ${category} company", {name: "Google", category: "Intenet"});
document.write(buf);// auto call toString method
console.log(buf);
console.log(StrBuf("static {0} method", "invoke"));